React State & Hooks

useState and immutable updates, batching, derived state, useEffect and its pitfalls, useRef, useMemo and useCallback, useReducer, context, custom hooks, the rules of hooks, and choosing a state management approach.

Intermediate 4 min readLesson 7 of 14 Interview Q&A

State is data that changes over time and affects what's rendered. Hooks are functions (named use…) that let function components hold state and hook into React features.

useState

TSX
function Counter() {
  const [count, setCount] = useState(0);
  return (
    <button onClick={() => setCount(count + 1)}>
      Clicked {count} times
    </button>
  );
}

Calling the setter schedules a re-render with the new value. State is a snapshot: within one render, count is a constant.

TSX
function handleClick() {
  setCount(count + 1);
  setCount(count + 1);       // both use the same snapshot: count goes up by 1, not 2
  setCount(c => c + 1);      // updater function: uses the latest pending value
}

React batches state updates inside the same event (and since React 18, everywhere), so several set calls cause one re-render.

Update state immutably

React decides whether to re-render by comparing references (Object.is). Mutating an object in place keeps the same reference — React may not notice:

TSX
const [todos, setTodos] = useState<Todo[]>([]);

// ✗ mutation
todos.push(newTodo); setTodos(todos);

// ✓ new arrays/objects
setTodos([...todos, newTodo]);                                         // add
setTodos(todos.filter(t => t.id !== id));                              // remove
setTodos(todos.map(t => t.id === id ? { ...t, done: !t.done } : t));   // update one
setUser(u => ({ ...u, address: { ...u.address, city: "Pune" } }));    // nested

(Libraries like Immer let you write "mutating" code that produces immutable updates.)

Don't store derived state

TSX
// ✗ duplicated state that can get out of sync
const [items, setItems] = useState([]);
const [count, setCount] = useState(0);

// ✓ compute it during render
const count = items.length;
const visible = items.filter(i => i.name.includes(query));   // memoise only if expensive

useEffect: synchronising with external systems

Effects run after the commit, to synchronise a component with something outside React: network requests, subscriptions, timers, manual DOM, analytics.

TSX
function ChatRoom({ roomId }: { roomId: string }) {
  useEffect(() => {
    const conn = createConnection(roomId);
    conn.connect();
    return () => conn.disconnect();      // cleanup: before re-running and on unmount
  }, [roomId]);                          // dependencies: re-run when roomId changes
  // …
}
DependenciesRuns
omittedAfter every render
[]After the first render (mount) only
[a, b]When a or b changed (by Object.is)

Fetching data in an effect (and its race condition)

TSX
useEffect(() => {
  let ignore = false;
  setLoading(true);
  fetch(`/api/users/${id}`)
    .then(r => r.json())
    .then(data => { if (!ignore) { setUser(data); setLoading(false); } });
  return () => { ignore = true; };      // a newer id started: ignore the stale response
}, [id]);

In real apps, prefer a data library (TanStack Query, SWR) or your framework's loader / Server Components (Rendering strategies), which handle caching, deduplication, race conditions and refetching.

useRef

A ref holds a mutable value that persists across renders without causing re-renders. Two uses:

TSX
// 1. Reference a DOM node
const inputRef = useRef<HTMLInputElement>(null);
<input ref={inputRef} />
<button onClick={() => inputRef.current?.focus()}>Focus</button>

// 2. Keep a mutable value (timer id, previous value, instance data)
const intervalRef = useRef<number>();
intervalRef.current = window.setInterval(tick, 1000);

Memoisation: useMemo, useCallback, memo

TSX
const sorted = useMemo(() => expensiveSort(items), [items]);     // cache a computed value
const onSelect = useCallback((id: string) => select(id), [select]);  // stable function identity
const Row = memo(function Row({ item, onSelect }) { /* … */ });  // skip re-render if props unchanged

These are performance optimisations, not semantics. Use them when profiling shows a slow render, or when a stable identity matters (dependencies of other hooks, props of memoised children). The React Compiler can insert this memoisation automatically.

useReducer

For state with complex transitions, centralise the logic in a reducer — a pure (state, action) → newState function (the same idea as Redux):

TSX
type State = { items: Item[]; status: "idle" | "loading" | "error" };
type Action =
  | { type: "loaded"; items: Item[] }
  | { type: "removed"; id: string }
  | { type: "failed" };

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case "loaded":  return { items: action.items, status: "idle" };
    case "removed": return { ...state, items: state.items.filter(i => i.id !== action.id) };
    case "failed":  return { ...state, status: "error" };
  }
}

const [state, dispatch] = useReducer(reducer, { items: [], status: "loading" });
dispatch({ type: "removed", id });

Context: avoiding prop drilling

Passing props through many layers that don't use them ("prop drilling") gets tedious. Context makes a value available to an entire subtree:

TSX
const ThemeContext = createContext<"light" | "dark">("light");

function App() {
  const [theme, setTheme] = useState<"light" | "dark">("dark");
  return (
    <ThemeContext.Provider value={theme}>
      <Page />
    </ThemeContext.Provider>
  );
}

function Button() {
  const theme = useContext(ThemeContext);     // any depth below the provider
  return <button className={theme}>OK</button>;
}

Every consumer re-renders when the context value changes, so context suits low-frequency, widely needed values (theme, current user, locale) — not rapidly changing state.

Custom hooks

Extract reusable stateful logic into your own hooks:

TSX
function useLocalStorage<T>(key: string, initial: T) {
  const [value, setValue] = useState<T>(() => {
    const saved = localStorage.getItem(key);
    return saved !== null ? JSON.parse(saved) : initial;
  });
  useEffect(() => { localStorage.setItem(key, JSON.stringify(value)); }, [key, value]);
  return [value, setValue] as const;
}

const [draft, setDraft] = useLocalStorage("draft", "");

Rules of hooks

  1. Call hooks only at the top level of a component or custom hook — not inside conditions, loops or nested functions.
  2. Call hooks only from React functions.

Why: React identifies each hook by its call order within a component. A conditional hook would shift the order between renders and mix up state. The ESLint plugin enforces these rules.

Choosing state management

State kindTool
Local UI state (open/closed, input value)useState / useReducer
Shared by a few nearby componentsLift state to the common parent
App-wide, rarely changing (theme, auth user)Context
Server data (fetched, cached, refetched)TanStack Query, SWR, framework loaders, Server Components
Complex global client stateZustand, Redux Toolkit, Jotai
URL state (filters, page, tab)The URL: search params and router
FormsReact Hook Form, native form actions

Most "global state" in typical apps is actually server cache; a data-fetching library removes most of the need for Redux-style stores.

Key takeaways
  • useState gives a snapshot per render; setters schedule re-renders and are batched; use updater functions for sequential updates.
  • Update objects and arrays immutably; compute derived values instead of storing them.
  • useEffect synchronises with external systems; clean up, list dependencies, and avoid unnecessary effects.
  • useRef holds DOM nodes or mutable values without re-rendering; useMemo/useCallback/memo are optimisations.
  • useReducer centralises complex transitions; context avoids prop drilling for low-frequency values.
  • Hooks must be called unconditionally at the top level because React tracks them by order.
Interview questions
QWhy must hooks not be called conditionally?medium

React stores each component's hook state in an ordered list and matches hook calls to entries by their position on every render. If a hook is skipped on some renders, every later hook shifts position and reads another hook's state, causing wrong values or crashes. Calling hooks unconditionally at the top level keeps the order stable.

QWhat is the cleanup function in useEffect for?easy

It undoes what the effect set up — unsubscribing, closing connections, clearing timers, aborting requests. React runs it before re-running the effect with new dependencies and when the component unmounts, preventing leaks, duplicate subscriptions and updates from stale async work.