Automatic memoization
- React course
- Expert
- Lesson 2/32
- 4 min
Learn that you no longer need to write useMemo and useCallback by hand.
Automatic memoization
Without the React Compiler a callback is recreated on every render; even a child wrapped in memo re-renders due to the new reference. You prevent this manually with useCallback.
With the compiler enabled this is automatic: the callback is recreated only when its dependencies change. The code is more readable and performance more consistent.
Derived arrays and objects are also memoized automatically.
Callbacks without useCallback
With the compiler enabled a button click handler is not recreated on every render. When you write onClick={() => setFilter('done')} the compiler wraps it with a stable reference automatically.
This prevents unnecessary re-renders of children wrapped in memo. You no longer need to write useCallback by hand.
Still, make sure dependencies are correct; the compiler does not fix wrong dependencies.
Practice Write the TodoList component
Write TodoList. Take todos and filter props. Compute visible with filter === 'all' ? todos : todos.filter(t => t.done). Show <button onClick={() => setFilter('done')}>Done</button> and inside a <ul> map visible to <li key={t.id}>{t.text}</li>. Export it.
Starter code
// Write the TodoList component hereSample solution
import { useState } from 'react';
function TodoList({ todos }) {
const [filter, setFilter] = useState('all');
const visible = filter === 'all' ? todos : todos.filter(t => t.done);
return (
<div>
<button onClick={() => setFilter('done')}>Done</button>
<ul>{visible.map(t => <li key={t.id}>{t.text}</li>)}</ul>
</div>
);
}
export default TodoList;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Fill in the blank: compute the filtered list
function TodoList({ todos, filter }) {
const visible = filter === 'all' ? todos : todos.____(t => t.done);
return <ul>{visible.map(t => <li key={t.id}>{t.text}</li>)}</ul>;
}
function TodoList({ todos, filter }) {
const visible = filter === 'all' ? todos : todos.filter(t => t.done);
return <ul>{visible.map(t => <li key={t.id}>{t.text}</li>)}</ul>;
}
Explanation: todos.filter selects items by condition.
2 What do you no longer need to write with the React Compiler?
- useState
- import
- useMemo and useCallback Correct answer
- export
Explanation: The compiler handles memoization automatically.
3 Match memoization concepts
| Term | Meaning |
|---|---|
useCallback |
Manual wrap |
compiler |
Wraps automatically |
memo |
Caches child |
dependency |
Triggers recalc on change |