Performance: Updating state
This affects how quickly the UI updates after user interaction and how smoothly the app responds to input.
const [state, setState] = useState({ count: 0, text: '' }); function updateBoth() { setState(prev => ({ ...prev, count: prev.count + 1, text: 'Updated' })); }
const [count, setCount] = useState(0); const [text, setText] = useState(''); function updateBoth() { setCount(count + 1); setText('Updated'); }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Multiple separate state updates | Multiple updates to virtual DOM | Multiple reflows triggered | Higher paint cost due to repeated updates | [X] Bad |
| Single batched state update | One update to virtual DOM | Single reflow triggered | Lower paint cost with one update | [OK] Good |
count using the useState hook in React?useState hook returns a pair: the current state and a function to update it.setCount(newValue).setCount(newValue) to update the state. -> Option Aname with value "John" using useState?useState hook returns an array with two elements: the state variable and the setter function.const [name, setName] = useState('John'); to get both the value and setter.import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
const handleClick = () => {
setCount(count + 1);
setCount(count + 1);
};
return (
<>
{count}
Increment
</>
);
}setCount(count + 1) calls use the same count value (0) because state updates are batched.count becomes 1, not 2.import React, { useState } from 'react';
function Toggle() {
const [isOn, setIsOn] = useState(false);
function handleClick() {
isOn = !isOn;
}
return {isOn ? 'ON' : 'OFF'};
}isOn = !isOn; directly, which is not allowed for state variables.setIsOn(!isOn);.user with a new age property without losing other properties. Which is the correct way to update state using setUser?const [user, setUser] = useState({ name: 'Alice', age: 25 });
// Update age to 26setUser(prevUser => ({ ...prevUser, age: 26 })) to merge old properties with new age.Pass the test and this pattern moves unknown