learn deep. ship safe.Practice testsFollow ByteMunSubscribe

Concept

State

Data that changes over time and makes the UI re-render, and where to keep it.

State explained

State is the data a component remembers between renders and that changes over time, such as form input, a selected tab or fetched data. In React, updating state with its setter tells React to re-render. State management is deciding where each piece of state lives so the right components can read it without passing it everywhere.

Where state can live

  • Local state with useState or useReducer: the default. Keep state in the lowest component that needs it.
  • Lifted state: when siblings need the same data, move it to their closest common parent and pass it down.
  • Context: for values many components need, such as the current user or theme.
  • A store (Redux, Zustand and similar): for large shared client state with many updates.
  • Server state: data from an API is best handled by a data-fetching library or framework that caches, refetches and deduplicates it.
  • URL state: filters, search terms, tabs and page numbers kept in the query string survive a reload and can be shared or bookmarked as a link.
function Cart() {
  const [items, setItems] = useState([]);
  const total = items.reduce((sum, i) => sum + i.price, 0); // derived: not state
  const add = (item) => setItems((prev) => [...prev, item]); // immutable update
  return <Summary items={items} total={total} onAdd={add} />;
}

Common mistakes

  • Storing derived values such as totals or filtered lists in state. Compute them during render instead.
  • Duplicating state in two places, which then drift out of sync.
  • Mutating state instead of creating new objects and arrays.
  • Putting everything in a global store, so every update re-renders far more than needed.

What interviewers ask about state

  • "State versus props?" State is owned and changed by the component; props are passed in and read-only.
  • "When would you lift state up?" When two components need the same changing data.
  • "Context or a state library?" Context for occasional, app-wide values; a store for frequent updates to shared data.
Concept map
Learn firstProps
State

What should you learn before State?

  1. JSXHTML-like syntax inside JavaScript that compiles to React element calls.
  2. Components and compositionBuilding a UI from small reusable pieces and combining them.
  3. PropsInputs passed from a parent component to a child.

What to learn after State

  • FormsControlled and uncontrolled inputs, validation and submission in React.
  • React hooksFunctions such as useState and useEffect that add state and lifecycle to function components.
  • RenderingState changes are what trigger renders.

Practise State

All topics