Created
July 26, 2020 12:03
-
-
Save bengrunfeld/11519bb63c8596cf1014489cf2dc581e to your computer and use it in GitHub Desktop.
useCallback helps us prevent unnecessary re-renders
This file contains hidden or 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
import { useState, useCallback } from "react"; | |
const CountDisplay = ({ count }) => <h3>Count: {count}</h3>; | |
const CountButton = React.memo(({ updateCount }) => { | |
// Note that this line will now only execute once on initial render! | |
console.log("=> CountButton render", Date.now()); | |
return <button onClick={() => updateCount()}>Increment</button>; | |
}); | |
const CounterApp = () => { | |
const [count, setCount] = useState(0); | |
const updateCount = useCallback(() => { | |
setCount((c) => c + 1); | |
}, [setCount]); | |
return ( | |
<> | |
<CountButton updateCount={updateCount} /> | |
<CountDisplay count={count} /> | |
</> | |
); | |
}; | |
export default CounterApp; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment