useState·续2
return ( <> <input value={text} onChange={e => setText(e.target.value)} /> <button onClick={() => { setText(''); setTodos([{ id: todos.length, text: text }, ...todos]); }}>Add</button> <ul> {todos.map(item => ( <li key={item.id}> {item.text} </li> ))} </ul> </> ); }
#### Passing the initial state directly
This example **does not** pass the initializer function, so the `createInitialTodos` function runs on every render, such as when you type into the input. There is no observable difference in behavior, but this code is less efficient.
```js
import { useState } from 'react';
function createInitialTodos() {
const initialTodos = [];
for (let i = 0; i < 50; i++) {
initialTodos.push({
id: i,
text: 'Item ' + (i + 1)
});
}
return initialTodos;
}
export default function TodoList() {
const [todos, setTodos] = useState(createInitialTodos());
const [text, setText] = useState('');
return (
<>
<input
value={text}
onChange={e => setText(e.target.value)}
/>
<button onClick={() => {
setText('');
setTodos([{
id: todos.length,
text: text
}, ...todos]);
}}>Add</button>
<ul>
{todos.map(item => (
<li key={item.id}>
{item.text}
</li>
))}
</ul>
</>
);
}
Resetting state with a key
You'll often encounter the key attribute when rendering lists. However, it also serves another purpose.
You can reset a component's state by passing a different key to a component. In this example, the Reset button changes the version state variable, which we pass as a key to the Form. When the key changes, React re-creates the Form component (and all of its children) from scratch, so its state gets reset.
Read preserving and resetting state to learn more.
```js src/App.js import { useState } from 'react';
export default function App() { const [version, setVersion] = useState(0);
function handleReset() { setVersion(version + 1); }
return ( <> <button onClick={handleReset}>Reset</button> <Form key={version} /> </> ); }
function Form() { const [name, setName] = useState('Taylor');
return ( <> <input value={name} onChange={e => setName(e.target.value)} /> <p>Hello, {name}.</p> </> ); }
```css
button { display: block; margin-bottom: 20px; }
Storing information from previous renders
Usually, you will update state in event handlers. However, in rare cases you might want to adjust state in response to rendering -- for example, you might want to change a state variable when a prop changes.
In most cases, you don't need this:
- If the value you need can be computed entirely from the current props or other state, remove that redundant state altogether. If you're worried about recomputing too often, the
useMemoHook can help. - If you want to reset the entire component tree's state, pass a different
keyto your component. - If you can, update all the relevant state in the event handlers.
In the rare case that none of these apply, there is a pattern you can use to update state based on the values that have been rendered so far, by calling a set function while your component is rendering.
Here's an example. This CountLabel component displays the count prop passed to it:
```js src/CountLabel.js export default function CountLabel({ count }) { return <h1>{count}</h1> }
Say you want to show whether the counter has *increased or decreased* since the last change. The `count` prop doesn't tell you this -- you need to keep track of its previous value. Add the `prevCount` state variable to track it. Add another state variable called `trend` to hold whether the count has increased or decreased. Compare `prevCount` with `count`, and if they're not equal, update both `prevCount` and `trend`. Now you can show both the current count prop and *how it has changed since the last render*.
```js src/App.js
import { useState } from 'react';
import CountLabel from './CountLabel.js';
export default function App() {
const [count, setCount] = useState(0);
return (
<>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
<button onClick={() => setCount(count - 1)}>
Decrement
</button>
<CountLabel count={count} />
</>
);
}
```js src/CountLabel.js active import { useState } from 'react';
export default function CountLabel({ count }) { const [prevCount, setPrevCount] = useState(count); const [trend, setTrend] = useState(null); if (prevCount !== count) { setPrevCount(count); setTrend(count > prevCount ? 'increasing' : 'decreasing'); } return ( <> <h1>{count}</h1> {trend && <p>The count is {trend}</p>} </> ); }
```css
button { margin-bottom: 10px; }
Note that if you call a set function while rendering, it must be inside a condition like prevCount !== count, and there must be a call like setPrevCount(count) inside of the condition. Otherwise, your component would re-render in a loop until it crashes. Also, you can only update the state of the currently rendering component like this. Calling the set function of another component during rendering is an error. Finally, your set call should still update state without mutation -- this doesn't mean you can break other rules of pure functions.
This pattern can be hard to understand and is usually best avoided. However, it's better than updating state in an effect. When you call the set function during render, React will re-render that component immediately after your component exits with a return statement, and before rendering the children. This way, children don't need to render twice. The rest of your component function will still execute (and the result will be thrown away). If your condition is below all the Hook calls, you may add an early return; to restart rendering earlier.
Troubleshooting
I've updated the state, but logging gives me the old value
Calling the set function does not change state in the running code:
```js {4,5,8} function handleClick() { console.log(count); // 0
setCount(count + 1); // Request a re-render with 1 console.log(count); // Still 0!
setTimeout(() => { console.log(count); // Also 0! }, 5000); }
This is because [states behaves like a snapshot.](/learn/state-as-a-snapshot) Updating state requests another render with the new state value, but does not affect the `count` JavaScript variable in your already-running event handler.
If you need to use the next state, you can save it in a variable before passing it to the `set` function:
```js
const nextCount = count + 1;
setCount(nextCount);
console.log(count); // 0
console.log(nextCount); // 1
I've updated the state, but the screen doesn't update
React will ignore your update if the next state is equal to the previous state, as determined by an Object.is comparison. This usually happens when you change an object or an array in state directly:
obj.x = 10; // 🚩 Wrong: mutating existing object
setObj(obj); // 🚩 Doesn't do anything
You mutated an existing obj object and passed it back to setObj, so React ignored the update. To fix this, you need to ensure that you're always replacing objects and arrays in state instead of mutating them:
// ✅ Correct: creating a new object
setObj({
...obj,
x: 10
});
I'm getting an error: "Too many re-renders"
You might get an error that says: Too many re-renders. React limits the number of renders to prevent an infinite loop. Typically, this means that you're unconditionally setting state during render, so your component enters a loop: render, set state (which causes a render), render, set state (which causes a render), and so on. Very often, this is caused by a mistake in specifying an event handler:
```js {1-2} // 🚩 Wrong: calls the handler during render return <button onClick={handleClick()}>Click me</button>
// ✅ Correct: passes down the event handler return <button onClick={handleClick}>Click me</button>
// ✅ Correct: passes down an inline function return <button onClick={(e) => handleClick(e)}>Click me</button>
If you can't find the cause of this error, click on the arrow next to the error in the console and look through the JavaScript stack to find the specific `set` function call responsible for the error.
---
### My initializer or updater function runs twice
In [Strict Mode](/reference/react/StrictMode), React will call some of your functions twice instead of once:
```js {2,5-6,11-12}
function TodoList() {
// This component function will run twice for every render.
const [todos, setTodos] = useState(() => {
// This initializer function will run twice during initialization.
return createTodos();
});
function handleClick() {
setTodos(prevTodos => {
// This updater function will run twice for every click.
return [...prevTodos, createTodo()];
});
}
// ...
This is expected and shouldn't break your code.
This development-only behavior helps you keep components pure. React uses the result of one of the calls, and ignores the result of the other call. As long as your component, initializer, and updater functions are pure, this shouldn't affect your logic. However, if they are accidentally impure, this helps you notice the mistakes.
For example, this impure updater function mutates an array in state:
```js {2,3} setTodos(prevTodos => { // 🚩 Mistake: mutating state prevTodos.push(createTodo()); });
Because React calls your updater function twice, you'll see the todo was added twice, so you'll know that there is a mistake. In this example, you can fix the mistake by [replacing the array instead of mutating it](#updating-objects-and-arrays-in-state):
```js {2,3}
setTodos(prevTodos => {
// ✅ Correct: replacing with new state
return [...prevTodos, createTodo()];
});
Now that this updater function is pure, calling it an extra time doesn't make a difference in behavior. This is why React calling it twice helps you find mistakes. Only component, initializer, and updater functions need to be pure. Event handlers don't need to be pure, so React will never call your event handlers twice.
Read keeping components pure to learn more.
I'm trying to set state to a function, but it gets called instead
You can't put a function into state like this:
const [fn, setFn] = useState(someFunction);
function handleClick() {
setFn(someOtherFunction);
}
Because you're passing a function, React assumes that someFunction is an initializer function, and that someOtherFunction is an updater function, so it tries to call them and store the result. To actually store a function, you have to put () => before them in both cases. Then React will store the functions you pass.
```js {1,4} const [fn, setFn] = useState(() => someFunction);
function handleClick() { setFn(() => someOtherFunction); } ```
