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

Gotcha: React useState initializer runs only once

Submitted by: @anonymous··
0
Viewed 0 times
usestate initiallazy initializerstate resetkey propstate from props

Error Messages

state not updating with new props
stale initial state
useState not resetting

Problem

React useState initial value is only used on the first render. Passing new props doesn't reset the state.

Solution

useState initialization behavior:

// GOTCHA: Initial value ignored after first render
function UserProfile({ userId }) {
  const [user, setUser] = useState(null);
  // FIX: Use useEffect to sync with props
  useEffect(() => {
    fetchUser(userId).then(setUser);
  }, [userId]);
}

// GOTCHA: Expensive computation on every render
// BAD: computeInitial() runs every render, result discarded
const [data, setData] = useState(computeExpensiveInitial());

// GOOD: Lazy initializer - function runs only once
const [data, setData] = useState(() => computeExpensiveInitial());

// GOTCHA: Resetting state when props change
function EditForm({ item }) {
  const [draft, setDraft] = useState(item.name);
  // draft doesn't update when item prop changes!

  // FIX 1: Use key to force remount
  // <EditForm key={item.id} item={item} />

  // FIX 2: Sync with useEffect
  useEffect(() => {
    setDraft(item.name);
  }, [item.id]);

  // FIX 3: Derive from props (if no local editing needed)
  const displayName = item.name;
}

Why

useState captures the initial value at mount time. This is by design - state persists across renders. When you need state to follow props, use key, useEffect, or derive from props directly.

Context

React state management

Revisions (0)

No revisions yet.