Skip to content

Instantly share code, notes, and snippets.

@bengrunfeld
Created July 26, 2020 12:03
Show Gist options
  • Save bengrunfeld/11519bb63c8596cf1014489cf2dc581e to your computer and use it in GitHub Desktop.
Save bengrunfeld/11519bb63c8596cf1014489cf2dc581e to your computer and use it in GitHub Desktop.
useCallback helps us prevent unnecessary re-renders
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