Last active
May 25, 2020 16:00
-
-
Save vzaidman/a0aa2d5193c654e84ddd985ae33c7df2 to your computer and use it in GitHub Desktop.
Advanced React- useCallback() Invalidates Too Often in Practice #14099
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
const PureHeavyComponent = React.memo(({onClick}) => { | |
console.log('pure heavy component!'); | |
return ( | |
<div onClick={onClick}> | |
//Many Other React elements are created here | |
</div> | |
); | |
}); | |
const Parent = () => { | |
console.log('parent!'); | |
const [count, setCount] = React.useState(0); | |
// returns a new instance of handleClick whenever count changes | |
const handleClick = React.useCallback(() => console.log(`hi #${count}!`), [count]); | |
return ( | |
<> | |
<PureHeavyComponent onClick={handleClick} /> | |
<button onClick={() => setCount(count + 1)}> | |
increase counter | |
</button> | |
</> | |
); | |
}; | |
// results: | |
// first render: | |
<Parent/> | |
// parent! | |
// pure heavy component! | |
// next renders as a result of clicking "increase counter": | |
<Parent/> | |
// parent! | |
// pure heavy component! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment