useMemo·续2
```js src/TodoList.js active import List from './List.js'; import { filterTodos } from './utils.js'
export default function TodoList({ todos, theme, tab }) { const visibleTodos = filterTodos(todos, tab); return (
```js src/List.js
import { memo } from 'react';
function List({ items }) {
return (
<ul>
{items.map(item => (
<li key={item.id}>
{item.completed ?
<s>{item.text}</s> :
item.text
}
</li>
))}
</ul>
);
}
export default memo(List);
```js src/utils.js export function createTodos() { const todos = []; for (let i = 0; i < 50; i++) { todos.push({ id: i, text: "Todo " + (i + 1), completed: Math.random() > 0.5 }); } return todos; }
export function filterTodos(todos, tab) { return todos.filter(todo => { if (tab === 'all') { return true; } else if (tab === 'active') { return !todo.completed; } else if (tab === 'completed') { return todo.completed; } }); }
```css
label {
display: block;
margin-top: 10px;
}
.dark {
background-color: black;
color: white;
}
.light {
background-color: white;
color: black;
}
Quite often, code without memoization works fine. If your interactions are fast enough, you don't need memoization.
Keep in mind that you need to run React in production mode, disable React Developer Tools, and use devices similar to the ones your app's users have in order to get a realistic sense of what's actually slowing down your app.
Preventing an Effect from firing too often
Sometimes, you might want to use a value inside an Effect:
```js {4-7,10} function ChatRoom({ roomId }) { const [message, setMessage] = useState('');
const options = { serverUrl: 'https://localhost:1234', roomId: roomId }
useEffect(() => { const connection = createConnection(options); connection.connect(); // ...
This creates a problem. [Every reactive value must be declared as a dependency of your Effect.](/learn/lifecycle-of-reactive-effects#react-verifies-that-you-specified-every-reactive-value-as-a-dependency) However, if you declare `options` as a dependency, it will cause your Effect to constantly reconnect to the chat room:
```js {5}
useEffect(() => {
const connection = createConnection(options);
connection.connect();
return () => connection.disconnect();
}, [options]); // 🔴 Problem: This dependency changes on every render
// ...
To solve this, you can wrap the object you need to call from an Effect in useMemo:
```js {4-9,16} function ChatRoom({ roomId }) { const [message, setMessage] = useState('');
const options = useMemo(() => { return { serverUrl: 'https://localhost:1234', roomId: roomId }; }, [roomId]); // ✅ Only changes when roomId changes
useEffect(() => { const connection = createConnection(options); connection.connect(); return () => connection.disconnect(); }, [options]); // ✅ Only changes when options changes // ...
This ensures that the `options` object is the same between re-renders if `useMemo` returns the cached object.
However, since `useMemo` is performance optimization, not a semantic guarantee, React may throw away the cached value if [there is a specific reason to do that](#caveats). This will also cause the effect to re-fire, **so it's even better to remove the need for a function dependency** by moving your object *inside* the Effect:
```js {5-8,13}
function ChatRoom({ roomId }) {
const [message, setMessage] = useState('');
useEffect(() => {
const options = { // ✅ No need for useMemo or object dependencies!
serverUrl: 'https://localhost:1234',
roomId: roomId
}
const connection = createConnection(options);
connection.connect();
return () => connection.disconnect();
}, [roomId]); // ✅ Only changes when roomId changes
// ...
Now your code is simpler and doesn't need useMemo. Learn more about removing Effect dependencies.
Memoizing a dependency of another Hook
Suppose you have a calculation that depends on an object created directly in the component body:
```js {2} function Dropdown({ allItems, text }) { const searchOptions = { matchMode: 'whole-word', text };
const visibleItems = useMemo(() => { return searchItems(allItems, searchOptions); }, [allItems, searchOptions]); // 🚩 Caution: Dependency on an object created in the component body // ...
Depending on an object like this defeats the point of memoization. When a component re-renders, all of the code directly inside the component body runs again. **The lines of code creating the `searchOptions` object will also run on every re-render.** Since `searchOptions` is a dependency of your `useMemo` call, and it's different every time, React knows the dependencies are different, and recalculate `searchItems` every time.
To fix this, you could memoize the `searchOptions` object *itself* before passing it as a dependency:
```js {2-4}
function Dropdown({ allItems, text }) {
const searchOptions = useMemo(() => {
return { matchMode: 'whole-word', text };
}, [text]); // ✅ Only changes when text changes
const visibleItems = useMemo(() => {
return searchItems(allItems, searchOptions);
}, [allItems, searchOptions]); // ✅ Only changes when allItems or searchOptions changes
// ...
In the example above, if the text did not change, the searchOptions object also won't change. However, an even better fix is to move the searchOptions object declaration inside of the useMemo calculation function:
```js {3} function Dropdown({ allItems, text }) { const visibleItems = useMemo(() => { const searchOptions = { matchMode: 'whole-word', text }; return searchItems(allItems, searchOptions); }, [allItems, text]); // ✅ Only changes when allItems or text changes // ...
Now your calculation depends on `text` directly (which is a string and can't "accidentally" become different).
---
### Memoizing a function
Suppose the `Form` component is wrapped in [`memo`.](/reference/react/memo) You want to pass a function to it as a prop:
```js {2-7}
export default function ProductPage({ productId, referrer }) {
function handleSubmit(orderDetails) {
post('/product/' + productId + '/buy', {
referrer,
orderDetails
});
}
return <Form onSubmit={handleSubmit} />;
}
Just as {} creates a different object, function declarations like function() {} and expressions like () => {} produce a different function on every re-render. By itself, creating a new function is not a problem. This is not something to avoid! However, if the Form component is memoized, presumably you want to skip re-rendering it when no props have changed. A prop that is always different would defeat the point of memoization.
To memoize a function with useMemo, your calculation function would have to return another function:
```js {2-3,8-9} export default function Page({ productId, referrer }) { const handleSubmit = useMemo(() => { return (orderDetails) => { post('/product/' + productId + '/buy', { referrer, orderDetails }); }; }, [productId, referrer]);
return
