useCallback
This stops the function increment from being recreated every render
const increment = useCallback(() => setCount(c => c+ 1), [])
-------
const handleAddTodo = useCallback((text) => {
const newTodo = { id: nextId++, text };
setTodos([...todos, newTodo]);
}, [todos]);
Introduction to useCallback
The useCallback
and useMemo
Hooks are similar.
The main difference is that useMemo
returns a memoized value and useCallback
returns a memoized function.
useCallback is a React Hook that lets you cace a function definition between re-renders.
The useCallback
Hook only runs when one of its dependencies update.
Good points
This allows us to isolate resource intensive functions so that they will not automatically run on every render.
This can improve performance.
Check this out with the profiler.
https://www.w3schools.com/react/react_usecallback.asp
Notes
Sometimes you can use an updater function.
const [age, setAge] = useState(42);
function increment() {
setAge(a => a + 1);
}