Managing UI State
useState, controlled inputs, deriving values instead of storing them twice, and lazy initial state.
ReadModule 2 of 7
A component function runs from the top on every render, so it can't remember anything by itself. Hooks are how it asks React to remember things (useState, useReducer, useRef), to do things after rendering (useEffect, useLayoutEffect) and to stay stable between renders (useMemo, useCallback, useId). This module builds them up on the product store: a search box, a back button, a cart badge, favorites, a zoom effect, review forms, a cart with undo, and a cart page that re-renders more than it should.
Every log, order of calls and "before/after" in these notes was recorded by running the product store in Chrome (examples/product-store/src/lessons/hooks).
Two facts explain most hook behavior: each render is a separate function call with its own values (closures), and React compares things with Object.is (dependencies, memo props, state). Keep both in mind while reading.
Read them in order. Each one builds on the ones before it.
useState, controlled inputs, deriving values instead of storing them twice, and lazy initial state.
ReaduseEffect for syncing with the outside world, and the cleanup that stops listeners from piling up.
ReadMount, update, unmount: the recorded order of renders, layout effects, effects and cleanups.
ReadMove state up so siblings can share it, and back down (colocate) when only one component needs it.
ReaduseRef and ref callbacks for real DOM nodes, and why object dependencies make effects re-run.
ReadUpdater functions, immutable updates, saving to localStorage and an undo history, in one cart.
ReadIndependent values → useState; values that change together → useReducer. The stale-closure bug that decides it.
ReadWhat triggers a re-render, why memo fails on new objects, stale closures, and when to use useMemo/useCallback.
Read