|
1 | 1 | ---
|
2 |
| -title: Explain what happens when `setState` is called in React |
| 2 | +title: Explain what happens when the `useState` setter function is called in React |
3 | 3 | ---
|
4 | 4 |
|
5 | 5 | ## TL;DR
|
6 | 6 |
|
7 |
| -When `setState` is called in React, it schedules an update to the component's state object. React then merges the new state with the current state and triggers a re-render of the component. This process is asynchronous, meaning the state change might not happen immediately. React batches multiple `setState` calls for performance optimization. |
| 7 | +When the setter function returned by the `useState` hook is called in React, it schedules an update to the component's state value. React then queues a re-render of the component with the new state. This process is typically asynchronous, and React batches multiple state updates together for performance. |
8 | 8 |
|
9 | 9 | ---
|
10 | 10 |
|
11 |
| -## What happens when `setState` is called in React |
| 11 | +## What happens when the `useState` setter is called |
12 | 12 |
|
13 | 13 | ### State update scheduling
|
14 | 14 |
|
15 |
| -When `setState` is called, React schedules an update to the component's state. This means that the state change does not happen immediately. Instead, React marks the component as needing an update and will process the state change later. |
| 15 | +When you call the setter function provided by `useState` (e.g., `setCount`), React schedules an update for that specific state variable. This doesn't happen instantly; React marks the component as needing to re-render with the updated state value. |
16 | 16 |
|
17 | 17 | ```javascript
|
18 |
| -this.setState({ count: this.state.count + 1 }); |
| 18 | +const [count, setCount] = useState(0); |
| 19 | +// ... |
| 20 | +setCount(count + 1); // Schedules an update to set 'count' to 1 |
19 | 21 | ```
|
20 | 22 |
|
21 |
| -### Merging state |
| 23 | +### State replacement |
22 | 24 |
|
23 |
| -React merges the new state with the current state. The `setState` method performs a shallow merge, meaning it only updates the properties specified in the new state object and leaves the rest unchanged. |
| 25 | +The `useState` setter function **replaces** the old state value entirely with the new value you provide. If your state is an object and you only want to update one property, you need to manually spread the old state and override the specific property. |
24 | 26 |
|
25 | 27 | ```javascript
|
26 |
| -this.setState({ name: 'John' }); |
27 |
| -// Only the 'name' property is updated, other state properties remain the same |
| 28 | +const [user, setUser] = useState({ name: 'Anon', age: 99 }); |
| 29 | + |
| 30 | +// To update only name, you must spread the old state: |
| 31 | +setUser((prevState) => ({ ...prevState, name: 'John' })); |
| 32 | +// If you just did setUser({ name: 'John' }), the 'age' property would be lost. |
28 | 33 | ```
|
29 | 34 |
|
30 | 35 | ### Re-rendering
|
31 | 36 |
|
32 |
| -After merging the state, React triggers a re-render of the component. The component's `render` method is called, and the virtual DOM is updated. React then compares the virtual DOM with the actual DOM and makes the necessary updates to the actual DOM. |
33 |
| - |
34 |
| -### Asynchronous nature |
35 |
| - |
36 |
| -The `setState` method is asynchronous. React batches multiple `setState` calls for performance optimization. This means that if you call `setState` multiple times in a row, React may combine them into a single update. |
37 |
| - |
38 |
| -```javascript |
39 |
| -this.setState({ count: this.state.count + 1 }); |
40 |
| -this.setState({ count: this.state.count + 1 }); |
41 |
| -// React may batch these updates into a single update |
42 |
| -``` |
| 37 | +After scheduling the state update(s), React will eventually trigger a re-render of the component. The functional component body is executed again with the new state value(s). React updates its virtual DOM, compares it with the previous version, and efficiently updates the actual DOM only where necessary. |
43 | 38 |
|
44 |
| -### Callback function |
| 39 | +### Asynchronous nature and Batching |
45 | 40 |
|
46 |
| -You can pass a callback function as the second argument to `setState`. This function will be called after the state has been updated and the component has re-rendered. |
| 41 | +State updates triggered by `useState` setters are typically asynchronous and batched. If you call multiple state setters in the same event handler or effect, React will often batch these updates together into a single re-render pass for better performance. Because of this, you shouldn't rely on the state variable having its new value immediately after calling the setter. If the new state depends on the previous state, use the functional update form. |
47 | 42 |
|
48 | 43 | ```javascript
|
49 |
| -this.setState({ count: this.state.count + 1 }, () => { |
50 |
| - console.log('State updated and component re-rendered'); |
51 |
| -}); |
| 44 | +// Assume count is 0 |
| 45 | +setCount(count + 1); // Queues update to 1 |
| 46 | +setCount(count + 1); // Still sees count as 0, queues update to 1 again! |
| 47 | +// Result might be 1, not 2 |
| 48 | + |
| 49 | +// Correct way using functional update: |
| 50 | +setCount((prevCount) => prevCount + 1); // Queues update based on previous state |
| 51 | +setCount((prevCount) => prevCount + 1); // Queues another update based on the result of the first |
| 52 | +// Result will be 2 |
52 | 53 | ```
|
53 | 54 |
|
54 | 55 | ## Further reading
|
55 | 56 |
|
56 |
| -- [React documentation on setState](https://react.dev/reference/react/useState#setstate) |
57 |
| -- [Understanding setState in React](https://medium.com/@baphemot/understanding-react-setstate-a4640451865b) |
58 |
| -- [React's setState explained](https://daveceddia.com/where-fetch-data-componentwillmount-vs-componentdidmount/) |
| 57 | +- [React Docs: Using the State Hook (`useState`)](https://react.dev/reference/react/useState) |
| 58 | +- [React Docs: Queueing multiple state updates](https://react.dev/reference/react/useState#updating-state-based-on-the-previous-state) |
0 commit comments