Fix React Component Not Re-rendering on State Change
Problem
React component is not re-rendering when state changes, causing the UI to not update even though the state value has changed.
Root Cause
This usually happens when you mutate state directly instead of creating new objects/arrays, or when state updates are not properly handled in functional components.
Solution
Here are the most common causes and solutions:
Problem 1: Direct State Mutation
// ❌ Wrong - mutating state directly
const [items, setItems] = useState([]);
const addItem = (newItem) => {
items.push(newItem); // Direct mutation
setItems(items); // React won't detect the change
};
// ✅ Correct - create new array
const addItem = (newItem) => {
setItems([...items, newItem]); // New array reference
};
Problem 2: Mutating Object State
// ❌ Wrong
const [user, setUser] = useState({ name: '', email: '' });
const updateName = (newName) => {
user.name = newName; // Direct mutation
setUser(user); // React won't detect the change
};
// ✅ Correct
const updateName = (newName) => {
setUser({ ...user, name: newName }); // New object reference
};
Problem 3: useEffect Dependencies
// ❌ Wrong - missing dependencies
useEffect(() => {
fetchData(userId);
}, []); // Missing userId dependency
// ✅ Correct
useEffect(() => {
fetchData(userId);
}, [userId]); // Include all dependencies
Problem 4: State Updates in Loops
// ❌ Wrong - state updates not batched properly
items.forEach(item => {
setCount(count + item.value); // Using stale state
});
// ✅ Correct - use functional updates
items.forEach(item => {
setCount(prevCount => prevCount + item.value);
});