Reading — step 1 of 5
Read
useState Hook
A hook is a function that adds state/effects to a function component.
Implementation: tied to the component instance.
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:
setState(callback) for safe updates:
Lazy initial state:
Reducer pattern (useReducer):
- For complex state (forms, lists).
- dispatch(action) → state.
Same hook semantics; different mental model.
Context (useContext):
- Pass data through tree without manual prop drilling.
- Provider at top; consumers anywhere below.
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…