Created
July 27, 2024 17:35
-
-
Save wchargin/063795252f8fe4c57b10ba0459a133a7 to your computer and use it in GitHub Desktop.
useStable with quick-exit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<div id="root" /> | |
<script type="module"> | |
import React, { | |
createElement as h, | |
useState, | |
} from "https://esm.sh/react@18?dev"; | |
import { createRoot } from "https://esm.sh/react-dom@18/client?dev"; | |
const lazyEq = (a, b) => JSON.stringify(a) === JSON.stringify(b); | |
const useStable = (input, eq) => { | |
const [previous, setPrevious] = useState(input); | |
if (eq(input, previous)) { | |
console.log("equal:", previous); | |
return previous; | |
} else { | |
console.log("unequal: setPrevious ->", input); | |
setPrevious(input); | |
return input; | |
} | |
}; | |
const App = () => { | |
console.log("rendering App"); | |
const [num, setNum] = useState(1); | |
const unstablePowers = [num, num ** 2, num ** 3]; | |
const powers = useStable(unstablePowers, lazyEq); | |
const onClick = () => { | |
console.log("clicky clicky"); | |
setNum(num + 1); | |
}; | |
return h( | |
"div", | |
{ style: { display: "flex", flexDirection: "column" } }, | |
h("button", { onClick }, "Bigger!"), | |
h(Numbers, { numbers: powers }), | |
); | |
}; | |
const Numbers = ({ numbers }) => { | |
console.log("rendering Numbers"); | |
console.log("---"); | |
return h("span", {}, "Your numbers are: ", JSON.stringify(numbers)); | |
}; | |
createRoot(root).render(h(App)); | |
</script> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
rendering App | |
equal: Array(3) [ 1, 1, 1 ] | |
rendering Numbers | |
--- | |
clicky clicky | |
rendering App | |
unequal: setPrevious -> Array(3) [ 2, 4, 8 ] | |
rendering App | |
equal: Array(3) [ 2, 4, 8 ] | |
rendering Numbers | |
--- |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment