Skip to content

Instantly share code, notes, and snippets.

@bengrunfeld
Last active July 26, 2020 11:58
Show Gist options
  • Save bengrunfeld/cfe8adfef8155dab9de5c73298708c92 to your computer and use it in GitHub Desktop.
Save bengrunfeld/cfe8adfef8155dab9de5c73298708c92 to your computer and use it in GitHub Desktop.
Passing functions as props causes unnecessary re-renders
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