State, Effects and Hooks
Manage local and shared state with useState, useReducer and context, and use effects only for real synchronisation with the outside world.
Intermediate · about 10 hours · difficulty 3/5
Learn first: React Fundamentals
State is data that changes over time and should re-render the UI. Getting state right is most of what "good React" means.
Core hooks
- useState for local values. Updates are asynchronous and replace the value, so create new objects and arrays rather than mutating.
- useReducer when state has several related fields and named actions, like a multi-step application form.
- useContext to share values such as the current user or theme without passing props through every level.
- useRef for values that should not trigger re-renders, and for DOM references.
Effects
useEffect synchronises a component with something outside React: a subscription, a timer, a browser API. It is not the place to compute derived values or to fetch every bit of data. If a value can be computed from props or state, compute it during render.
Where state lives
Keep state as close as possible to where it is used, lift it up only when siblings need it, and keep server data in a dedicated tool (covered later). Global state libraries like Zustand are optional; many apps never need one.
Pitfalls
- Effects with missing dependencies, causing stale values, or with too many, causing infinite loops.
- Storing derived values (like a filtered list) in state.
- Reaching for context for everything, which re-renders large parts of the tree.
You are ready to move on when you can explain why a component re-rendered, and refactor an effect-heavy component so most of its logic runs during render.
Key concepts
- useState and immutable updates
- useReducer
- useContext
- useRef
- useEffect and cleanup
- Derived state
- Custom hooks
- Zustand for global state
Mini project
Add filters (branch, stipend range, remote) and a saved-internships list to your board. Keep filters in the URL, saved items in context, and extract a reusable useDebounce custom hook for search.
Check yourself
You store a filtered list in state and update it in an effect whenever filters change. What is wrong with that, and what should you do instead?
Free resources
- Managing State (React)
- You Might Not Need an Effect (React)
- Hooks API Reference (React)