ReactEasy
What is state?
State is data that a component remembers between renders and that can change over time, such as form input, a toggle, fetched results or the current step of a wizard. In function components you create it with useState or useReducer; calling the setter tells React to re-render the component with the new value.
Characteristics
- Local and private: each instance of a component has its own state.
- Persistent across renders: unlike regular variables, which reset every render.
- Triggers re-renders when updated with a different value (compared with
Object.is). - A snapshot: during one render, the state value is fixed. Setting state schedules the next render; it does not change the variable in the current one.
What belongs in state
- Values that change and affect what is rendered.
- Not things you can compute from props or other state (derive them instead).
- Not values that never change (constants) or that do not affect rendering (use
useRef).
Updating correctly
- Replace, do not mutate:
setUser({ ...user, name }),setList([...list, item]). - Use the updater form when the next value depends on the previous:
setCount((c) => c + 1). - Group related values in one object or use
useReducerfor complex transitions.
Where else state lives
URL (search params), server cache (TanStack Query, SWR), context or stores (Zustand, Redux) for shared global state, and form libraries for form state.
Code example
tsx
1import { useState } from "react";23type Step = "cart" | "address" | "payment";45export function Checkout() {6 const [step, setStep] = useState<Step>("cart");7 const [address, setAddress] = useState({ city: "", zip: "" });89 let normalVariable = 0; // resets to 0 on every render; changing it never re-renders1011 return (12 <div>13 <p>Step: {step}</p>14 {step === "address" && (15 <input16 placeholder="City"17 value={address.city}18 onChange={(e) => setAddress({ ...address, city: e.target.value })} // new object19 />20 )}21 <button onClick={() => setStep(step === "cart" ? "address" : "payment")}>Next</button>22 <button onClick={() => normalVariable++}>Does nothing visible ({normalVariable})</button>23 </div>24 );25}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.