πŸŽ‰ 75% of content is free forever β€” Unlock Premium from $10/mo β†’
CW
NEWSLIVESearch All Content
πŸ’Ό Servicesℹ️ Aboutβœ‰οΈ ContactView Pricing Plansfrom $10

React Hooks: Effects, Context, Refs, and Custom Hooks

React🟒 Free Lesson

React Hooks

Hooks let function components do everything class components once did β€” hold state, subscribe to external systems, run side effects β€” while making that logic reusable. useState gets most of the attention, but the hooks that unlock real applications are useEffect, useContext, useRef, and the memoization pair useMemo/useCallback. Add the ability to bundle your own hooks, and shared logic stops being copy-paste.

The difficulty with hooks is not syntax; it is timing. Effects run after render, not during it. Context updates propagate to consumers, not through every intermediate prop. Refs change without triggering renders. This lesson drills each of those timing models until they feel obvious.

The Mental Model: Render, Then Commit

Every React render is a two-phase process. First React calls your component function with the current props and state, producing a description of the UI. Then, if anything differs from the last description, React commits the minimal DOM updates. Effects run after commit, once the browser has painted the result of that render β€” which is why an effect can safely measure DOM nodes.

Strict Mode in development intentionally double-invokes effects to surface missing cleanup functions. If your effect "runs twice" only in development, that is the safety net working, not a bug in your code.

useEffect: Subscribing to the World Outside React

Use useEffect for anything React does not own: network requests, timers, event subscriptions, browser APIs, third-party widgets. The function you pass runs after commit; if it returns a cleanup function, that runs before the next run and on unmount.

import { useEffect, useState } from "react";

function useOnlineStatus() {
  const [online, setOnline] = useState(navigator.onLine);

  useEffect(() => {
    function goOnline() {
      setOnline(true);
    }
    function goOffline() {
      setOnline(false);
    }

    window.addEventListener("online", goOnline);
    window.addEventListener("offline", goOffline);

    return () => {
      window.removeEventListener("online", goOnline);
      window.removeEventListener("offline", goOffline);
    };
  }, []);

  return online;
}

function ConnectionBanner() {
  const online = useOnlineStatus();
  if (online) return null;
  return <p role="alert">You are offline. Changes will sync later.</p>;
}

The cleanup is not optional ceremony. Without it, a component that mounts, unmounts, and remounts β€” route changes, strict mode, fast refresh β€” accumulates listeners and timers until the page crawls. Every subscription your effect creates should be torn down in the returned function.

Dependency Arrays Done Right

The optional second argument lists every reactive value the effect reads. Omitting it runs the effect after every render; an empty array runs it once after mount (plus cleanup on unmount). Anything in between must list all dependencies β€” React's lint rules exist to hold you to that.

import { useEffect, useState } from "react";

function UserPanel({ userId }) {
  const [user, setUser] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    const controller = new AbortController();

    setUser(null);
    setError(null);

    fetch("/api/users/" + userId, { signal: controller.signal })
      .then((response) => {
        if (!response.ok) throw new Error("Request failed");
        return response.json();
      })
      .then((data) => setUser(data))
      .catch((err) => {
        if (err.name !== "AbortError") setError(err.message);
      });

    return () => controller.abort();
  }, [userId]);

  if (error) return <p role="alert">{error}</p>;
  if (!user) return <p>Loading profile…</p>;
  return <h2>{user.name}</h2>;
}

Three habits make this pattern bulletproof. Reset dependent state (setUser(null)) when the key input changes, so stale data from the previous request never flashes. Abort in-flight requests in cleanup, so a slow old response cannot overwrite a fast new one. Keep the dependency array honest β€” values created inside the render (objects, arrays, functions) need useMemo or useCallback to stay referentially stable, or you will re-run the effect forever.

useContext: Skipping the Middle Managers

Context shares a value across a subtree without prop drilling. Create it once, provide it at the top, and read it anywhere below:

import { createContext, useContext, useMemo, useState } from "react";

const ThemeContext = createContext("light");

export function ThemeProvider({ children }) {
  const [theme, setTheme] = useState("light");

  const value = useMemo(
    () => ({ theme, toggle: () => setTheme((t) => (t === "light" ? "dark" : "light")) }),
    [theme]
  );

  return <ThemeProvider value={value}>{children}</ThemeProvider>;
}

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

Packaging the raw useContext call into a useTheme wrapper centralizes the null check and gives consumers one import. Keep context values small and stable β€” every consumer re-renders when the value changes, so a large, frequently rebuilt object becomes a performance drag.

useRef: Values That Do Not Trigger Renders

A ref is a mutable box whose .current can change without causing a re-render. That makes it the right tool for two jobs: holding DOM node references, and keeping values that are purely operational (ids, timers, previous props) rather than visual.

import { useEffect, useRef, useState } from "react";

function SearchBox({ onSearch }) {
  const [query, setQuery] = useState("");
  const inputRef = useRef(null);
  const lastCallRef = useRef(0);

  useEffect(() => {
    inputRef.current.focus();
  }, []);

  function handleSubmit(event) {
    event.preventDefault();
    const now = Date.now();
    if (now - lastCallRef.current < 300) return; // crude debounce guard
    lastCallRef.current = now;
    onSearch(query);
  }

  return (
    <form onSubmit={handleSubmit}>
      <input
        ref={inputRef}
        value={query}
        onChange={(event) => setQuery(event.target.value)}
        aria-label="Search products"
      />
      <button type="submit">Search</button>
    </form>
  );
}

Never read or write .current during render for anything visual β€” two renders with the same props should produce the same tree, and refs break that promise silently.

useMemo and useCallback: When They Pay Off

useMemo(() => compute(a, b), [a, b]) caches a computed value between renders; useCallback(fn, [deps]) caches the function itself. Both cost memory and bookkeeping, so treat them as solutions to measured problems: wrapping expensive calculations that run on every render, or stabilizing identities that land in dependency arrays or memoized children.

import { useMemo } from "react";

function InvoiceTable({ lines, taxRate }) {
  const rows = useMemo(
    () =>
      lines.map((line) => ({
        ...line,
        total: line.qty * line.price,
        tax: line.qty * line.price * taxRate,
      })),
    [lines, taxRate]
  );

  const grand = useMemo(
    () => rows.reduce((sum, row) => sum + row.total + row.tax, 0),
    [rows]
  );

  return (
    <table>
      <tbody>
        {rows.map((row) => (
          <tr key={row.id}>
            <td>{row.label}</td>
            <td>{row.total.toFixed(2)}</td>
          </tr>
        ))}
      </tbody>
      <tfoot>
        <tr>
          <td>Grand total</td>
          <td>{grand.toFixed(2)}</td>
        </tr>
      </tfoot>
    </table>
  );
}

Extracting Custom Hooks

A custom hook is a function whose name starts with use and that calls other hooks. The moment two components share effect logic, lift it:

import { useEffect, useState } from "react";

export function useFetchJson(url) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const controller = new AbortController();
    setLoading(true);

    fetch(url, { signal: controller.signal })
      .then((res) => res.json())
      .then((json) => {
        setData(json);
        setLoading(false);
      })
      .catch(() => {});

    return () => controller.abort();
  }, [url]);

  return { data, loading };
}

Good custom hooks are narrow and composable: useOnlineStatus, useMediaQuery, useLocalStorage, useDebouncedValue. Name them after the state they provide, keep side effects inside, and expose plain values β€” consumers should not need to know which hooks are underneath.

useId, useTransition, and useDeferredValue

Beyond the core hooks, three additions have become daily tools. useId generates a unique, stable identifier per component instance β€” the answer to the label-and-input pairing problem in component libraries, where hard-coded ids collide the moment the component renders twice on one page.

useTransition marks a state update as non-urgent. The input keeps responding immediately while a heavy list re-renders in the background, and the pending flag tells you when to show a subtle busy hint. It does not make the work faster; it keeps urgent work responsive while non-urgent work queues behind it. useDeferredValue is the read-side counterpart: passing a deferred copy of a value into an expensive subtree lets the old content stay interactive during the update.

import { useId, useTransition, useDeferredValue, useState } from "react";

function SearchField({ query, onQueryChange, results }) {
  const inputId = useId();
  const hintId = useId() + "-hint";
  const [isPending, startTransition] = useTransition();
  const deferredQuery = useDeferredValue(query);

  function handleChange(event) {
    const next = event.target.value;
    startTransition(() => {
      onQueryChange(next);
    });
  }

  return (
    <div>
      <label htmlFor={inputId}>Search the catalog</label>
      <input
        id={inputId}
        value={query}
        onChange={handleChange}
        aria-describedby={hintId}
      />
      <p id={hintId}>
        {isPending ? "Updating results…" : "Results update as you type"}
      </p>
      <ResultList query={deferredQuery} results={results} />
    </div>
  );
}

Where the transition hook wraps the update, the deferred-value hook wraps the consumer β€” reach for it when the expensive component receives its value through props you do not control. The two compose naturally in search interfaces: local keystrokes stay snappy, results recompute when the main thread breathes, and the pending state stays honest rather than decorative.

⚠️A cleanup checklist for every effect

Train yourself to audit each effect against the same four questions. What did this effect subscribe to, and is that subscription removed in the returned function? What timer or interval did it start, and is it cleared? What in-flight request did it launch, and can that request be cancelled so a stale response never overwrites fresh state? Does the dependency array list every value the effect actually reads, including props and state referenced anywhere in the callback? An effect that answers all four cleanly will survive fast refresh, route changes, and strict mode's double invocation without leaking anything. An effect that cannot answer one of them is a production incident wearing a lab coat, waiting for the right mounting sequence to reveal itself.

Common Mistakes

Effects without cleanup for subscriptions and timers

Fix: Return a cleanup function from every effect that registers listeners, intervals, or abortable requests.

Empty dependency arrays around effects that read changing props

Fix: List every dependency honestly; restructure with useMemo/useCallback when identities drift.

Writing to a ref during render

Fix: Mutate refs only in effects or event handlers β€” render must stay pure.

Wrapping everything in useMemo and useCallback 'for performance'

Fix: Memoize only after measuring; each wrapper adds its own overhead.

Interview Questions

Q1: When does an effect run relative to paint, and why does it matter?

Effects run after React commits the render to the DOM, after the browser paints. That timing makes it safe to measure nodes and subscribe to the DOM without blocking updates.

Q2: What does the dependency array actually control?

It declares the reactive values the effect closes over. React compares them by Object.is between renders and re-runs the effect (with prior cleanup) when any change.

Q3: When is useRef better than useState?

When the value must persist across renders but should not trigger re-renders when changed β€” DOM nodes, timers, previous values, abort controllers.

Q4: How do you share effect logic between components?

Extract a custom hook β€” a use-prefixed function that calls hooks internally and returns values or helpers.

Key Takeaways

  • Effects run after commit; always return cleanup for anything the effect subscribes or starts.
  • Dependency arrays must list every reactive value the effect reads β€” the lint rule is your ally.
  • Abort in-flight work on cleanup and reset dependent state when inputs change to avoid stale flashes.
  • Context replaces prop drilling but re-renders all consumers β€” keep values small and stable.
  • Refs hold mutable operational state that must not cause renders.
  • Memoization tools solve measured problems; custom hooks solve duplicated logic.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

β€”
β˜†β˜†β˜†β˜†β˜†
0 ratings

Rate & Feedback

Need Expert Web Development Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement