Performance: Multiple state variables
This affects how React updates the UI and manages rendering performance when state changes.
const [count, setCount] = useState(0); const [text, setText] = useState(''); function updateCount() { setCount(prev => prev + 1); } function updateText(newText) { setText(newText); }
const [state, setState] = useState({ count: 0, text: '' }); function updateCount() { setState(prev => ({ ...prev, count: prev.count + 1 })); } function updateText(newText) { setState(prev => ({ ...prev, text: newText })); }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Single large state object | One update triggers full component re-render | Multiple reflows if many DOM nodes depend on state | Higher paint cost due to full update | [X] Bad |
| Multiple independent state variables | Updates trigger minimal re-rendering | Fewer reflows limited to changed parts | Lower paint cost with targeted updates | [OK] Good |
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
const [text, setText] = useState('Hello');
function handleClick() {
setCount(count + 1);
setText(text + '!');
}
return (
<div>
<p>Count: {count}</p>
<p>Text: {text}</p>
<button onClick={handleClick}>Click</button>
</div>
);
}import React, { useState } from 'react';
function Example() {
const [count, setCount] = useState(0);
const [name, setName] = useState('');
function update() {
setCount(count + 1);
setName = 'John';
}
return <button onClick={update}>Update</button>;
}Pass the test and this pattern moves unknown