Last active
July 26, 2020 11:58
-
-
Save bengrunfeld/cfe8adfef8155dab9de5c73298708c92 to your computer and use it in GitHub Desktop.
Passing functions as props causes 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 } from "react"; | |
const CountDisplay = ({ count }) => <h3>Count: {count}</h3>; | |
const CountButton = ({ updateCount }) => { | |
// Note that this line will fire every time, | |
// showing us that an unneeded re-render has occurred. | |
console.log("=> CountButton render", Date.now()); | |
return <button onClick={() => updateCount()}>Increment</button>; | |
} | |
const OneFileApp = () => { | |
const [count, setCount] = useState(0); | |
const updateCount = () => setCount((c) => c + 1); | |
return ( | |
<> | |
<CountButton updateCount={updateCount} /> | |
<CountDisplay count={count} /> | |
</> | |
); | |
}; | |
export default OneFileApp; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment