Reputation: 408
In React's Hooks API, it was suggested that future react implementation may choose to forget memorized values and that the code should work before optimization with useMemo().
My question is, what would be a good example in which the code works without useMemo(), performs better with useMemo, and continue to work if useMemo forget memorized values?
You can visit the original page here, a screenshot is also posted in case the page is updated in the future.
Upvotes: 1
Views: 128
Reputation: 2957
Please keep in mind that is example is contrived.
function App() {
let [first, setFirst] = React.useState(1);
let [second, setSecond] = React.useState(1);
let [sum, setSum] = React.useState(undefined);
let total = function expensive(x, y) {
console.log("computing");
return parseInt(first) + parseInt(second);
};
let add = () => {
setSum(total);
};
return (
<div className="App">
<input
onChange={e => setFirst(e.target.value)}
type="number"
value={first}
/>
<input
onChange={e => setSecond(e.target.value)}
type="number"
value={second}
/>
<button onClick={add}>ADD</button>
<h2>{sum}</h2>
</div>
);
}
If you run this code, and smash the "ADD" button, you'll notice that "computing" logs every time, even though first
and second
have not changed. This code works without using useMemo
, but is not optimal. There's an optimization we can make.
Consider this change:
let total = React.useMemo(function expensive(x, y) {
console.log("computing");
return parseInt(first) + parseInt(second);
}, [first, second]);
Notice that "computing" only logs once, as the return value is being memoized. It will only recalculate when first
or second
changes. This will continue to work without useMemo
.
Examples like this are exactly what useMemo
is for -- a simple optimization. With or without that your code would still be run just fine.
"You may rely on useMemo as a performance optimization" - https://reactjs.org/docs/hooks-reference.html#usememo
Hope this helps! :)
https://codesandbox.io/s/elegant-chandrasekhar-nzqfx?fontsize=14&hidenavigation=1&theme=dark
Upvotes: 1