The best practice for updating the state in React is to use the state updater function when the new state depends on the previous state. This ensures that updates are based on the latest state and prevents issues due to asynchronous updates.
-
Use functional updates with
setState
oruseState
: This approach ensures that even if multiple updates are queued, each update gets the latest state.setCount(prevCount => prevCount + 1);
-
Avoid directly mutating the state: Instead of modifying the state object directly (which won’t trigger a rerender), always return a new object or array when updating the state.
// Incorrect state.items.push(newItem); // This mutates the existing state setItems(state.items); // Won't trigger re-render // Correct setItems(prevItems => [...prevItems, newItem]); // Creates a new array
-
Batch updates when necessary: React may batch multiple state updates in one render to optimize performance. If multiple state updates rely on the same event, it is best to combine them when possible.
-
Use
useReducer
for complex state logic: If your component’s state logic is complex, consider using useReducer instead of useState to manage the state more predictably.