›bobbyencoded_
/posts/newsletter/courses/about
/posts/newsletter/courses/about

The Decode

The week's AI & software news, decoded.

Subscribe →

// © 2026 BobbyEncoded Inc. — A Canadian corporation

← Back to Blog

React Learning Path

React Learning Path, Part 2: How React Works Day to Day

November 8, 2026 · 11 min read

React, Interview Prep, TypeScript, State Management, Testing, Frontend

Part 1 covered the building blocks. This part is the everyday middle of React: not "what is state?" but "why did this component re-render?", "why is this effect firing twice?" and "where should this state live?"

What causes a re-render

A component re-renders when:

  1. Its state changes (a useState or useReducer setter is called with a new value).
  2. Its parent re-renders. By default, every child of a re-rendering component renders again, whether or not its props changed.
  3. A context it reads changes.

Props changing isn't really a separate cause: props only change because the parent re-rendered.

Rendering and updating the screen are two different steps:

  • Render phase: React calls your component functions to get the new UI description. This must be pure, and React may call it more than once.
  • Commit phase: React applies the differences to the DOM, then runs effects.

So a re-render isn't automatically expensive. If the output is the same, the DOM isn't touched. Re-renders become a problem when a component does heavy work while rendering or when thousands of them render at once. That's when memoization (below) earns its place.

Hooks beyond useState

The rules, and why they exist

Hooks must be called at the top level of a component or custom hook: not inside conditions, loops or nested functions. React doesn't know hooks by name; it identifies them by call order. The first useState call is slot 1, the second is slot 2, and so on. If a condition skips a hook on one render, every hook after it reads the wrong slot.

useRef: a value that survives renders without causing them

import { useEffect, useRef } from "react";

function AutoFocusInput() {
  const inputRef = useRef<HTMLInputElement>(null); // a ref to a DOM node
  const renders = useRef(0);                      // a mutable value; changing it doesn't re-render

  renders.current += 1;
  useEffect(() => inputRef.current?.focus(), []);

  return <input ref={inputRef} placeholder={`rendered ${renders.current} times`} />;
}

Use state for what the screen shows; use a ref for what it doesn't (timer ids, the previous value, a DOM node).

useReducer: when updates have rules

When state has several fields that change together, a reducer puts every transition in one place, and each transition is easy to test:

import { useReducer } from "react";

type State = { status: "idle" | "loading" | "success" | "error"; items: string[]; error?: string };
type Action =
  | { type: "fetch" }
  | { type: "resolved"; items: string[] }
  | { type: "rejected"; error: string };

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case "fetch":
      return { ...state, status: "loading", error: undefined };
    case "resolved":
      return { status: "success", items: action.items };
    case "rejected":
      return { ...state, status: "error", error: action.error };
  }
}

function useItems() {
  return useReducer(reducer, { status: "idle", items: [] });
}

A single status field also makes impossible states impossible: you can't be loading and in error at the same time, which two separate booleans would allow.

Custom hooks: reuse logic, not state

A custom hook is a function whose name starts with use and that calls other hooks. It shares logic; each component that calls it gets its own state.

import { useEffect, useState } from "react";

function useDebouncedValue<T>(value: T, delayMs = 300): T {
  const [debounced, setDebounced] = useState(value);

  useEffect(() => {
    const id = setTimeout(() => setDebounced(value), delayMs);
    return () => clearTimeout(id); // a new keystroke cancels the pending update
  }, [value, delayMs]);

  return debounced;
}

The effects you don't need

This is the single most useful thing I relearned. A lot of React bugs come from effects that shouldn't exist. The React docs have a whole page on it, "You Might Not Need an Effect". The short version:

1. Derived values belong in render, not in state plus an effect.

// Avoid: extra state, an extra render, and a moment where the two disagree
const [fullName, setFullName] = useState("");
useEffect(() => setFullName(`${first} ${last}`), [first, last]);

// Better: just compute it
const fullName = `${first} ${last}`;

If the computation is genuinely expensive, wrap it in useMemo, still without an effect.

2. Things caused by a user action belong in the event handler. "Send the analytics event when they click Buy" goes in the click handler, not in an effect that watches a purchased flag.

3. Effects that fetch must handle races. If the user switches from profile 1 to profile 2 quickly, the response for 1 can arrive last and overwrite 2. Ignore stale responses in the cleanup:

import { useEffect, useState } from "react";

type User = { id: number; name: string };

function useUser(userId: number) {
  const [user, setUser] = useState<User | null>(null);

  useEffect(() => {
    const controller = new AbortController();
    fetch(`/api/users/${userId}`, { signal: controller.signal })
      .then((res) => res.json() as Promise<User>)
      .then(setUser)
      .catch((err: unknown) => {
        if (err instanceof DOMException && err.name === "AbortError") return; // expected
        console.error(err);
      });
    return () => controller.abort(); // userId changed or we unmounted: cancel the old request
  }, [userId]);

  return user;
}

In real apps, use a data library for this (next section). But you should be able to write this version from memory and explain the abort.

4. Stale closures. An effect or callback sees the values from the render it was created in. An interval set up once with [] and reading count will read 0 forever. Fix it by listing the dependency, or by using the functional setter setCount(c => c + 1) so you don't need to read count at all.

Where should state live?

Start as low as possible, and lift state up to the closest common parent when two siblings need the same data. When that parent is far away and you're passing props through components that don't use them (prop drilling), you have three options, in this order:

  1. Composition first. Pass components as children so the middle layers don't have to forward props at all.
  2. Context for values many components read and that change rarely: theme, current user, locale.
  3. A store (Zustand, Redux Toolkit) for frequently changing, widely shared client state.
import { createContext, useContext, useState } from "react";

type Theme = "light" | "dark";
const ThemeContext = createContext<{ theme: Theme; toggle: () => void } | null>(null);

function ThemeProvider({ children }: { children: React.ReactNode }) {
  const [theme, setTheme] = useState<Theme>("light");
  const toggle = () => setTheme((t) => (t === "light" ? "dark" : "light"));
  return <ThemeContext value={{ theme, toggle }}>{children}</ThemeContext>; // React 19: no .Provider needed
}

function useTheme() {
  const ctx = useContext(ThemeContext);
  if (!ctx) throw new Error("useTheme must be used inside <ThemeProvider>");
  return ctx;
}

Context's catch: every component that reads it re-renders when its value changes. The object above is new on every render of ThemeProvider, so consumers re-render whenever the provider does. That's fine for a theme, but bad for state that changes on every keystroke. That's exactly where stores win: a component subscribes to just the slice it uses.

And one distinction that clears up most state debates: server state is not client state. Data from your API (users, orders) is a cache of something the server owns. It needs fetching, caching, refetching and invalidation. A data library handles that. Client state (is the modal open, which tab is selected) is small, and useState usually covers it.

Data fetching

For server state, TanStack Query (formerly React Query) is the common answer:

import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";

type Todo = { id: number; text: string };

function Todos() {
  const queryClient = useQueryClient();
  const { data, isPending, error } = useQuery({
    queryKey: ["todos"],                                         // the cache key
    queryFn: () => fetch("/api/todos").then((r) => r.json() as Promise<Todo[]>),
  });

  const addTodo = useMutation({
    mutationFn: (text: string) =>
      fetch("/api/todos", { method: "POST", body: JSON.stringify({ text }) }),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ["todos"] }), // refetch the list
  });

  if (isPending) return <p>Loading…</p>;
  if (error) return <p>Something went wrong.</p>;
  return (
    <>
      <ul>{data.map((t) => <li key={t.id}>{t.text}</li>)}</ul>
      <button onClick={() => addTodo.mutate("New task")}>Add</button>
    </>
  );
}

It gives you caching, de-duplication (ten components asking for ["todos"] make one request), background refetching, retries and race handling, which is everything the hand-written useUser above does badly or not at all.

Forms, routing and memoization, briefly

Forms. For anything beyond a couple of fields, React Hook Form plus a Zod schema is the common stack: the schema validates and gives you the TypeScript type from the same source. React 19 also adds form Actions; that's Part 3.

Routing. In React Router, URLs map to components; useParams reads path parameters like /users/:id, useNavigate changes route in code, and nested routes render into an <Outlet />. Treat the URL as state: filters and the current tab often belong in the query string so they survive refreshes and can be shared.

Memoization. Three tools, one purpose, which is skipping work:

  • React.memo(Component) skips re-rendering a child when its props are shallowly equal.
  • useMemo(() => compute(a, b), [a, b]) caches an expensive computed value.
  • useCallback(fn, [deps]) keeps the same function reference between renders, which only matters when that function is passed to a memoized child or used as an effect dependency.

They're not free (comparing dependencies costs something too) and they're easy to break: passing a new object literal to a memo child defeats it. Measure with the React DevTools Profiler first. Part 3 covers the React Compiler, which now does most of this for you.

Testing

React Testing Library's philosophy: test what the user sees and does, not implementation details. Query by role and label, the way a user (and a screen reader) finds things:

import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";

test("counter increments", async () => {
  render(<Counter />);
  await userEvent.click(screen.getByRole("button", { name: "+1" }));
  expect(screen.getByText("Clicked 1 times")).toBeInTheDocument();
});

Prefer getByRole over test ids, use findBy… (which waits) for things that appear after async work, and use queryBy… when asserting something is absent.

Check yourself: questions and answers

1. When does a component re-render?

When its state changes, when its parent re-renders, or when a context it uses changes. A re-render means React calls the function again; the DOM only changes if the output differs.

2. Why must hooks be called in the same order?

React stores hook state in a list per component and matches each call to its slot by position. Conditional hooks shift the positions, so state ends up in the wrong hook.

3. useEffect vs useLayoutEffect?

useEffect runs after the browser paints, so it doesn't block the screen. useLayoutEffect runs after the DOM updates but before paint. Use it only when you must measure layout and adjust before the user sees a flicker.

4. What's a stale closure, and how do you fix it?

A function captures the values from the render it was created in, so an effect or interval set up once keeps reading old values. Fix it by adding the value to the dependency array, or by using a functional state update so you don't read the value at all.

5. How do you avoid race conditions when fetching in an effect?

Cancel or ignore the previous request in the effect's cleanup, for example with an AbortController or an ignore flag. Better, use a data library that handles it.

6. Context vs Redux or Zustand?

Context passes values down the tree, but every consumer re-renders when the value changes, so it suits rarely changing values like theme or user. Stores let components subscribe to a slice, which suits frequently updated shared state. Server data belongs in a query cache, not in either.

7. useMemo vs useCallback?

useMemo caches the result of a function; useCallback caches the function itself. useCallback(fn, deps) is equivalent to useMemo(() => fn, deps).

8. What is prop drilling, and how do you avoid it?

Passing props through components that don't need them just to reach a deep child. Fix it with composition (children), context for app-wide values, or a store.

9. Why prefer getByRole in tests?

It finds elements the way users and assistive technology do, so tests survive refactors and double as an accessibility check.

10. When would you use useReducer over useState?

When several values change together, or the next state depends on rules you want in one testable function. A single status field also prevents impossible combinations.

Go deeper

  • React State and Hooks: hooks, rules and custom hooks in more depth
  • React Component Patterns: composition, compound components, render props and HOCs
  • React State Management: Context, Redux and Zustand
  • React API Integration: Data Fetching: React Query, mutations and pagination
  • React Forms and Validation: React Hook Form and Zod
  • React Router: Complete Navigation Guide
  • React Testing: Jest and React Testing Library

Next: Part 3, advanced React and React 19.

Further reading

  • React docs, You Might Not Need an Effect
  • React docs, Render and Commit and Rules of Hooks
  • TanStack Query, Overview
  • Testing Library, Guiding principles
← Previous

React Learning Path, Part 3: Advanced React and React 19

Next →

React Learning Path, Part 1: The Fundamentals

Thoughts on this?

Tell me on X: @bobbyencoded · Share this post on X

Want more like this? Subscribe to The Decode, a weekly email on the AI and developer news worth your time.