useCallback·续
return ( <div className={theme}> <ShippingForm onSubmit={handleSubmit} /> </div> ); }
function post(url, data) { // Imagine this sends a request... console.log('POST /' + url); console.log(data); }
```js {expectedErrors: {'react-compiler': [7, 8]}} src/ShippingForm.js
import { memo, useState } from 'react';
const ShippingForm = memo(function ShippingForm({ onSubmit }) {
const [count, setCount] = useState(1);
console.log('[ARTIFICIALLY SLOW] Rendering <ShippingForm />');
let startTime = performance.now();
while (performance.now() - startTime < 500) {
// Do nothing for 500 ms to emulate extremely slow code
}
function handleSubmit(e) {
e.preventDefault();
const formData = new FormData(e.target);
const orderDetails = {
...Object.fromEntries(formData),
count
};
onSubmit(orderDetails);
}
return (
<form onSubmit={handleSubmit}>
<p><b>Note: <code>ShippingForm</code> is artificially slowed down!</b></p>
<label>
Number of items:
<button type="button" onClick={() => setCount(count - 1)}>–</button>
{count}
<button type="button" onClick={() => setCount(count + 1)}>+</button>
</label>
<label>
Street:
<input name="street" />
</label>
<label>
City:
<input name="city" />
</label>
<label>
Postal code:
<input name="zipCode" />
</label>
<button type="submit">Submit</button>
</form>
);
});
export default ShippingForm;
label {
display: block; margin-top: 10px;
}
input {
margin-left: 5px;
}
button[type="button"] {
margin: 5px;
}
.dark {
background-color: black;
color: white;
}
.light {
background-color: white;
color: black;
}
Always re-rendering a component
In this example, the ShippingForm implementation is also artificially slowed down so that you can see what happens when some React component you're rendering is genuinely slow. Try incrementing the counter and toggling the theme.
Unlike in the previous example, toggling the theme is also slow now! This is because there is no useCallback call in this version, so handleSubmit is always a new function, and the slowed down ShippingForm component can't skip re-rendering.
```js src/App.js import { useState } from 'react'; import ProductPage from './ProductPage.js';
export default function App() { const [isDark, setIsDark] = useState(false); return ( <> <label> <input type="checkbox" checked={isDark} onChange={e => setIsDark(e.target.checked)} /> Dark mode </label> <hr /> <ProductPage referrerId="wizard_of_oz" productId={123} theme={isDark ? 'dark' : 'light'} /> </> ); }
```js src/ProductPage.js active
import ShippingForm from './ShippingForm.js';
export default function ProductPage({ productId, referrer, theme }) {
function handleSubmit(orderDetails) {
post('/product/' + productId + '/buy', {
referrer,
orderDetails,
});
}
return (
<div className={theme}>
<ShippingForm onSubmit={handleSubmit} />
</div>
);
}
function post(url, data) {
// Imagine this sends a request...
console.log('POST /' + url);
console.log(data);
}
```js {expectedErrors: {'react-compiler': [7, 8]}} src/ShippingForm.js import { memo, useState } from 'react';
const ShippingForm = memo(function ShippingForm({ onSubmit }) { const [count, setCount] = useState(1);
console.log('[ARTIFICIALLY SLOW] Rendering <ShippingForm />'); let startTime = performance.now(); while (performance.now() - startTime < 500) { // Do nothing for 500 ms to emulate extremely slow code }
function handleSubmit(e) { e.preventDefault(); const formData = new FormData(e.target); const orderDetails = { ...Object.fromEntries(formData), count }; onSubmit(orderDetails); }
return ( <form onSubmit={handleSubmit}> <p><b>Note: <code>ShippingForm</code> is artificially slowed down!</b></p> <label> Number of items: <button type="button" onClick={() => setCount(count - 1)}>–</button> {count} <button type="button" onClick={() => setCount(count + 1)}>+</button> </label> <label> Street: <input name="street" /> </label> <label> City: <input name="city" /> </label> <label> Postal code: <input name="zipCode" /> </label> <button type="submit">Submit</button> </form> ); });
export default ShippingForm;
```css
label {
display: block; margin-top: 10px;
}
input {
margin-left: 5px;
}
button[type="button"] {
margin: 5px;
}
.dark {
background-color: black;
color: white;
}
.light {
background-color: white;
color: black;
}
However, here is the same code with the artificial slowdown removed. Does the lack of useCallback feel noticeable or not?
```js src/App.js import { useState } from 'react'; import ProductPage from './ProductPage.js';
export default function App() { const [isDark, setIsDark] = useState(false); return ( <> <label> <input type="checkbox" checked={isDark} onChange={e => setIsDark(e.target.checked)} /> Dark mode </label> <hr /> <ProductPage referrerId="wizard_of_oz" productId={123} theme={isDark ? 'dark' : 'light'} /> </> ); }
```js src/ProductPage.js active
import ShippingForm from './ShippingForm.js';
export default function ProductPage({ productId, referrer, theme }) {
function handleSubmit(orderDetails) {
post('/product/' + productId + '/buy', {
referrer,
orderDetails,
});
}
return (
<div className={theme}>
<ShippingForm onSubmit={handleSubmit} />
</div>
);
}
function post(url, data) {
// Imagine this sends a request...
console.log('POST /' + url);
console.log(data);
}
```js src/ShippingForm.js import { memo, useState } from 'react';
const ShippingForm = memo(function ShippingForm({ onSubmit }) { const [count, setCount] = useState(1);
console.log('Rendering <ShippingForm />');
function handleSubmit(e) { e.preventDefault(); const formData = new FormData(e.target); const orderDetails = { ...Object.fromEntries(formData), count }; onSubmit(orderDetails); }
return ( <form onSubmit={handleSubmit}> <label> Number of items: <button type="button" onClick={() => setCount(count - 1)}>–</button> {count} <button type="button" onClick={() => setCount(count + 1)}>+</button> </label> <label> Street: <input name="street" /> </label> <label> City: <input name="city" /> </label> <label> Postal code: <input name="zipCode" /> </label> <button type="submit">Submit</button> </form> ); });
export default ShippingForm;
```css
label {
display: block; margin-top: 10px;
}
input {
margin-left: 5px;
}
button[type="button"] {
margin: 5px;
}
.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.
Updating state from a memoized callback
Sometimes, you might need to update state based on previous state from a memoized callback.
This handleAddTodo function specifies todos as a dependency because it computes the next todos from it:
```js {6,7} function TodoList() { const [todos, setTodos] = useState([]);
const handleAddTodo = useCallback((text) => { const newTodo = { id: nextId++, text }; setTodos([...todos, newTodo]); }, [todos]); // ...
You'll usually want memoized functions to have as few dependencies as possible. When you read some state only to calculate the next state, you can remove that dependency by passing an [updater function](/reference/react/useState#updating-state-based-on-the-previous-state) instead:
```js {6,7}
function TodoList() {
const [todos, setTodos] = useState([]);
const handleAddTodo = useCallback((text) => {
const newTodo = { id: nextId++, text };
setTodos(todos => [...todos, newTodo]);
}, []); // ✅ No need for the todos dependency
// ...
Here, instead of making todos a dependency and reading it inside, you pass an instruction about how to update the state (todos => [...todos, newTodo]) to React. Read more about updater functions.
Preventing an Effect from firing too often
Sometimes, you might want to call a function from inside an Effect:
```js {4-9,12} function ChatRoom({ roomId }) { const [message, setMessage] = useState('');
function createOptions() { return { serverUrl: 'https://localhost:1234', roomId: roomId }; }
useEffect(() => { const options = createOptions(); 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 `createOptions` as a dependency, it will cause your Effect to constantly reconnect to the chat room:
```js {6}
useEffect(() => {
const options = createOptions();
const connection = createConnection(options);
connection.connect();
return () => connection.disconnect();
}, [createOptions]); // 🔴 Problem: This dependency changes on every render
// ...
To solve this, you can wrap the function you need to call from an Effect into useCallback:
```js {4-9,16} function ChatRoom({ roomId }) { const [message, setMessage] = useState('');
const createOptions = useCallback(() => { return { serverUrl: 'https://localhost:1234', roomId: roomId }; }, [roomId]); // ✅ Only changes when roomId changes
useEffect(() => { const options = createOptions(); const connection = createConnection(options); connection.connect(); return () => connection.disconnect(); }, [createOptions]); // ✅ Only changes when createOptions changes // ...
This ensures that the `createOptions` function is the same between re-renders if the `roomId` is the same. **However, it's even better to remove the need for a function dependency.** Move your function *inside* the Effect:
```js {5-10,16}
function ChatRoom({ roomId }) {
const [message, setMessage] = useState('');
useEffect(() => {
function createOptions() { // ✅ No need for useCallback or function dependencies!
return {
serverUrl: 'https://localhost:1234',
roomId: roomId
};
}
const options = createOptions();
const connection = createConnection(options);
connection.connect();
return () => connection.disconnect();
}, [roomId]); // ✅ Only changes when roomId changes
// ...
Now your code is simpler and doesn't need useCallback. Learn more about removing Effect dependencies.
Optimizing a custom Hook
If you're writing a custom Hook, it's recommended to wrap any functions that it returns into useCallback:
```js {4-6,8-10} function useRouter() { const { dispatch } = useContext(RouterStateContext);
const navigate = useCallback((url) => { dispatch({ type: 'navigate', url }); }, [dispatch]);
const goBack = useCallback(() => { dispatch({ type: 'back' }); }, [dispatch]);
return { navigate, goBack, }; }
This ensures that the consumers of your Hook can optimize their own code when needed.
---
## Troubleshooting
### Every time my component renders, `useCallback` returns a different function
Make sure you've specified the dependency array as a second argument!
If you forget the dependency array, `useCallback` will return a new function every time:
```js {7}
function ProductPage({ productId, referrer }) {
const handleSubmit = useCallback((orderDetails) => {
post('/product/' + productId + '/buy', {
referrer,
orderDetails,
});
}); // 🔴 Returns a new function every time: no dependency array
// ...
This is the corrected version passing the dependency array as a second argument:
```js {7} function ProductPage({ productId, referrer }) { const handleSubmit = useCallback((orderDetails) => { post('/product/' + productId + '/buy', { referrer, orderDetails, }); }, [productId, referrer]); // ✅ Does not return a new function unnecessarily // ...
If this doesn't help, then the problem is that at least one of your dependencies is different from the previous render. You can debug this problem by manually logging your dependencies to the console:
```js {5}
const handleSubmit = useCallback((orderDetails) => {
// ..
}, [productId, referrer]);
console.log([productId, referrer]);
You can then right-click on the arrays from different re-renders in the console and select "Store as a global variable" for both of them. Assuming the first one got saved as temp1 and the second one got saved as temp2, you can then use the browser console to check whether each dependency in both arrays is the same:
Object.is(temp1[0], temp2[0]); // Is the first dependency the same between the arrays?
Object.is(temp1[1], temp2[1]); // Is the second dependency the same between the arrays?
Object.is(temp1[2], temp2[2]); // ... and so on for every dependency ...
When you find which dependency is breaking memoization, either find a way to remove it, or memoize it as well.
I need to call useCallback for each list item in a loop, but it's not allowed
Suppose the Chart component is wrapped in memo. You want to skip re-rendering every Chart in the list when the ReportList component re-renders. However, you can't call useCallback in a loop:
```js {expectedErrors: {'react-compiler': [6]}} {5-14} function ReportList({ items }) { return ( <article> {items.map(item => { // 🔴 You can't call useCallback in a loop like this: const handleClick = useCallback(() => { sendReport(item) }, [item]);
return ( <figure key={item.id}> <Chart onClick={handleClick} /> </figure> ); })} </article> ); }
Instead, extract a component for an individual item, and put `useCallback` there:
```js {5,12-21}
function ReportList({ items }) {
return (
<article>
{items.map(item =>
<Report key={item.id} item={item} />
)}
</article>
);
}
function Report({ item }) {
// ✅ Call useCallback at the top level:
const handleClick = useCallback(() => {
sendReport(item)
}, [item]);
return (
<figure>
<Chart onClick={handleClick} />
</figure>
);
}
Alternatively, you could remove useCallback in the last snippet and instead wrap Report itself in memo. If the item prop does not change, Report will skip re-rendering, so Chart will skip re-rendering too:
```js {5,6-8,15} function ReportList({ items }) { // ... }
const Report = memo(function Report({ item }) { function handleClick() { sendReport(item); }
return ( <figure> <Chart onClick={handleClick} /> </figure> ); }); ```
