React
Automatic memoization
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.
Exercise 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.
Show example 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;
Test yourself
-
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>;
}
Show answer
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>;
}
-
What do you no longer need to write with the React Compiler?
- useState
- import
- useMemo and useCallback
- export
Show answer
useMemo and useCallback — The compiler handles memoization automatically.
-
Match memoization concepts
- useCallback
- Manual wrap
- compiler
- Wraps automatically
- memo
- Caches child
- dependency
- Triggers recalc on change
Next lesson: Compatibility rules