Skip to content

Instantly share code, notes, and snippets.

@Pyrolistical
Last active October 4, 2021 00:28
Show Gist options
  • Save Pyrolistical/31a63ed608439c43c2d4d7201795662a to your computer and use it in GitHub Desktop.
Save Pyrolistical/31a63ed608439c43c2d4d7201795662a to your computer and use it in GitHub Desktop.
// React.memo caches the functional component if all the props are triple equals ===
const Increment = React.memo(({ caller, onClick }) => {
console.log(`${caller} button rendered`);
return <button onClick={onClick}>Increment</button>;
});
const BadComponent = () => {
const [count, setCount] = useState(0);
// declared functions never triple equals ===, even if its the same code
// ie. (() => {}) === (() => {}) is false,
// but when const x = () => {}; x === x is true
// increment is different render to render
const increment = () => setCount(count + 1);
return <>
<h2>BadComponent</h2>
<Increment caller="BadComponent" onClick={increment} />
<p>{count}</p>
</>;
};
const StillBadComponent = () => {
const [count, setCount] = useState(0);
// useCallback always returns a new function since count changes
const increment = useCallback(() => setCount(count + 1), [count]);
return <>
<h2>StillBadComponent</h2>
<Increment caller="StillBadComponent" onClick={increment} />
<p>{count}</p>
</>;
};
const GoodComponent = () => {
const [count, setCount] = useState(0);
// removed count dependency by passing a function into setCount
// increment is always the same function as dependency array is now empty
const increment = useCallback(() => setCount((count) => count + 1), []);
return <>
<h2>GoodComponent</h2>
<Increment caller="GoodComponent" onClick={increment} />
<p>{count}</p>
</>;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment