Give a memo child the same function every render with useCallback, and typing no longer re-renders the Save button.
React · intermediate · 7 min · 25 steps · free
import { memo, useCallback, useState } from 'react';
const SaveButton = memo(function SaveButton({ onSave }) {
return <button onClick={onSave}>Save</button>;
});
export default function Editor() {
const [text, setText] = useState('');
const [saves, setSaves] = useState(0);
const handleSave = useCallback(() => setSaves((s) => s + 1), []);
return (
<div>
<input value={text} onChange={(e) => setText(e.target.value)} placeholder="Write here" />
<SaveButton onSave={handleSave} />
<p>Saved {saves} times</p>
</div>
);
}<Editor> for the first time: it calls the Editor function.useState runs for the first time, so React stores the starting value for text and returns it: "".useState runs for the first time, so React stores the starting value for saves and returns it: 0.useCallback stores the function and returns it.Editor returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.<SaveButton> for the first time: it calls the SaveButton function. Its props: onSave = ƒ () => setSaves((s) => s + 1).SaveButton returns JSX: a description of what the screen should show, <button>Save</button>. React has not changed the page yet.text changes.setText(e.target.value) does not change text right away: React queues the update and will render again. In this call text is still "".<Editor> again (render 2): it calls Editor once more, from the top.useState returns the value React has kept for text: "Hi". The starting value is only used on the first render.useState returns the value React has kept for saves: 0. The starting value is only used on the first render.Editor returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.setSaves((s) => s + 1) queues an update function. React will call it with the latest saves when it renders again.<Editor> again (render 3): it calls Editor once more, from the top.useState returns the value React has kept for text: "Hi". The starting value is only used on the first render.s = 0. It returns 1, the new value.useState returns the value React has kept for saves: 1. The starting value is only used on the first render.useCallback gives back a remembered function for handleSave. It only makes a new one when a dependency changes.Editor returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.Answer: The same function every render
Answer: useMemo(() => fn, deps)
← useMemo: Caching a Calculation · Reducer + Context: an App Store →