useCallback
Stable functions.
Each render creates brand new functions. Usually that's fine. But a memoized child sees a new function as a changed prop, and renders anyway. Use callback keeps the same function between renders.
- New functions each render
- Child renders anyway
- useCallback
A stable add function
Add button is wrapped in memo, so it skips rendering when its props haven't changed. But a new function each render would count as a changed prop. Use callback keeps the same add function between renders. We type a note, and click add. Run it. The button rendered just once.
import { useState, useCallback, memo } from "react";
const AddButton = memo(function AddButton({ onAdd }) {
console.log("AddButton rendered");
return <button id="add" onClick={onAdd}>Add helmet</button>;
});
export default function App() {
const [count, setCount] = useState(0);
const [note, setNote] = useState("");
const add = useCallback(() => setCount(c => c + 1), []);
return (
<div>
<input id="n" value={note} onChange={e => setNote(e.target.value)} placeholder="Gift note" />
<AddButton onAdd={add} />
<p>Helmets: {count}</p>
</div>
);
}AddButton rendered
Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#61dafb;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}Also uses actions.json
[{"type": "#n", "text": "Hi"}, {"click": "#add"}]useMemo or useCallback
Use memo remembers a value, the result of calling a function. Use callback remembers the function itself. Use callback of f is the same as use memo of a function returning f.
useMemo
- Remembers a valueuseMemo(() => calc(), deps)Slow work
useCallback
- Remembers a functionuseCallback(fn, deps)Stable props
Summary
Use callback keeps a function stable, so memoized children can skip rendering. Next, memo.
Key takeaways- useCallback
- Same function
- Works with memo