Skip to content
useState Hook
step 1/5

Reading — step 1 of 5

Read

~1 min readHooks & State

useState Hook

A hook is a function that adds state/effects to a function component.

javascript

Implementation: tied to the component instance.

python

Each call to useState() corresponds to a slot in the component's state list.

Critical: hooks must be called in the SAME ORDER every render. That's why React forbids hooks inside conditions/loops.

When component re-renders:

  • Reset current_slot = 0.
  • Each useState() returns existing slot value.
  • New setter still works.

State persists across renders because state_slots persists per component instance.

Multiple useState:

python

setState(callback) for safe updates:

python

Lazy initial state:

python

Reducer pattern (useReducer):

  • For complex state (forms, lists).
  • dispatch(action) → state.
python

Same hook semantics; different mental model.

Context (useContext):

  • Pass data through tree without manual prop drilling.
  • Provider at top; consumers anywhere below.
python

Implementation: stack of provider values per context.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…