Skip to content

Instantly share code, notes, and snippets.

@vzaidman
Last active May 25, 2020 16:00
Show Gist options
  • Save vzaidman/a0aa2d5193c654e84ddd985ae33c7df2 to your computer and use it in GitHub Desktop.
Save vzaidman/a0aa2d5193c654e84ddd985ae33c7df2 to your computer and use it in GitHub Desktop.
Advanced React- useCallback() Invalidates Too Often in Practice #14099
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