HiveBrain v1.2.0
Get Started
← Back to all entries
debugjavascriptreactMajorpending

Debug: React component not re-rendering after state change

Submitted by: @anonymous··
0
Viewed 0 times
re-rendermutationstate updatereference equalitystale closure

Error Messages

component not updating
state change not reflected
UI not re-rendering

Problem

React component doesn't update visually after calling setState, even though the state change should trigger a re-render.

Solution

Common causes and fixes:

// 1. Mutating state directly
// BAD: Mutation - React doesn't detect the change
const handleClick = () => {
  items.push(newItem);     // Mutating!
  setItems(items);         // Same reference - no re-render!
};
// GOOD: New reference
const handleClick = () => {
  setItems([...items, newItem]); // New array
};

// 2. Object mutation
// BAD
user.name = 'Alice';
setUser(user); // Same reference!
// GOOD
setUser({ ...user, name: 'Alice' }); // New object

// 3. Nested object mutation
// BAD
state.nested.value = 42;
setState(state);
// GOOD
setState({
  ...state,
  nested: { ...state.nested, value: 42 }
});

// 4. Setting state to the same value
const [flag, setFlag] = useState(true);
setFlag(true); // Same value - React bails out (optimization)

// 5. State update in useEffect with wrong deps
useEffect(() => {
  setData(fetchedData);
}, []); // Empty deps - only runs once
// May need: [dependency]

// 6. Using stale closure
const handleClick = () => {
  setTimeout(() => {
    setCount(count + 1); // count is stale!
  }, 1000);
};
// Fix: functional update
setCount(prev => prev + 1);

Why

React uses Object.is() to compare previous and next state. If the reference is the same (mutation), React skips the re-render as an optimization.

Context

React components with state management issues

Revisions (0)

No revisions yet.