Skip to content

Search

Articles, tools, solutions and knowledge base guides

Start typing to search across articles, tools and apps.

React Hooks: A Practical Guide with Examples

React Hooks give function components access to state, context, external synchronization and rendering controls. Knowing the API names is not enough: the important decision is whether a problem concerns rendered data, an external resource or the cost of rendering. This guide uses small, independent examples to explain those choices and their production trade-offs.

Published Written by Reading time 9 min read
On this page Contents: quick navigation between sections

useState: render snapshots and the Rules of Hooks

import { useState } from "react";

export function QuantityPicker() {
  const [quantity, setQuantity] = useState(1);

  function addThree() {
    setQuantity((previous) => previous + 1);
    setQuantity((previous) => previous + 1);
    setQuantity((previous) => previous + 1);
  }

  return (
    <button type="button" onClick={addThree}>
      Quantity: {quantity} (+3)
    </button>
  );
}

Each render sees a snapshot of state. Calling a setter schedules an update rather than changing the variable already captured by the current code. Three calls to setQuantity(quantity + 1) using the same snapshot do not add three; three pure functional updaters, as below, are applied in sequence. Replace objects and arrays rather than mutating state. [3]

Call hooks at the top level of a component or custom hook, before conditional returns, not in loops or event handlers. React associates hook state with call order. The resource-reading use API is an exception that permits loops and conditions but not try/catch. Enable the rules-of-hooks lint. [1][16][18]

useReducer: centralize state transitions

import { useReducer } from "react";

const initialState = { quantity: 1, unitPrice: 25 };

export function cartReducer(state, action) {
  switch (action.type) {
    case "add":
      return { ...state, quantity: state.quantity + 1 };

    case "remove":
      return { ...state, quantity: Math.max(1, state.quantity - 1) };

    default:
      throw new Error(`Unknown action: ${action.type}`);
  }
}

export function Cart() {
  const [cart, dispatch] = useReducer(cartReducer, initialState);
  const total = cart.quantity * cart.unitPrice;

  return (
    <div>
      <button type="button" onClick={() => dispatch({ type: "remove" })}>
        Remove
      </button>
      <output>{total}</output>
      <button type="button" onClick={() => dispatch({ type: "add" })}>
        Add
      </button>
    </div>
  );
}

When several events change related fields, a reducer collects update rules in a pure function. The cart quantity cannot go below one. Each action describes an event; the reducer calculates the next state without mutation, HTTP requests or other side effects. [4]

The total is derived from quantity and price, so it does not need its own state. This avoids inconsistent values. A simple toggle still works well with useState; use a reducer when explicit transitions make complex update logic clearer and independently testable.

useEffect: synchronize with an external system

import { useEffect, useState } from "react";

export function Timer({ running }) {
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    if (!running) {
      return;
    }

    const intervalId = window.setInterval(() => {
      setSeconds((previous) => previous + 1);
    }, 1000);

    return () => {
      window.clearInterval(intervalId);
    };
  }, [running]);

  return <output>{seconds} s</output>;
}

A timer is a browser resource, so the effect creates it and cleanup releases it. Changing running cleans up the previous effect before setting up the new one; unmounting also triggers cleanup. In development, Strict Mode can exercise an additional setup, cleanup, setup cycle. [5]

Do not use an effect to calculate a total, filter a list or respond to a click. Derive values during rendering and handle user-triggered actions in event handlers. Dependencies follow the reactive values read by the effect, not a desired schedule. This timer counts callbacks rather than accurately measuring wall-clock time. [5][6]

useRef and useId: DOM access and accessibility

import { useId, useRef } from "react";

export function SearchField() {
  const inputId = useId();
  const inputRef = useRef(null);

  function focusInput() {
    inputRef.current?.focus();
  }

  return (
    <div>
      <label htmlFor={inputId}>Search</label>
      <input id={inputId} ref={inputRef} type="search" />
      <button type="button" onClick={focusInput}>
        Focus search
      </button>
    </div>
  );
}

useRef preserves a reference object across renders. Updating current does not trigger a render. Use it for DOM handles, timer identifiers or values that do not determine the displayed output. If a value needs to appear on screen, prefer state. Avoid reading or writing current during rendering except for predictable initialization. [7]

In the example, useId connects a label to its search field even if several instances are present. It is not a list key generator: use identifiers from the data for keys. Moving focus responds to a click, so it belongs in the handler rather than an effect. [8]

useContext: share data through the component tree

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

const ThemeContext = createContext("light");

function ThemeLabel() {
  const theme = useContext(ThemeContext);

  return <p>Theme: {theme}</p>;
}

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

  function toggleTheme() {
    setTheme((previous) => (previous === "light" ? "dark" : "light"));
  }

  return (
    <ThemeContext.Provider value={theme}>
      <button type="button" onClick={toggleTheme}>
        Switch theme
      </button>
      <ThemeLabel />
    </ThemeContext.Provider>
  );
}

Context reads the nearest matching provider without passing props through every intermediate component. The example supplies a simple theme identifier using .Provider, which also works with React 18. React 19 allows the context object itself to act as the provider. [9]

A changed provider value updates subscribing consumers; React compares values with Object.is. Creating a new object on every render can therefore cause unnecessary work. Consider separating values that update at different rates when measurements justify it. Context by itself does not provide a server-data cache.

useMemo, useCallback and memo: optimization, not correctness

import { memo, useCallback, useMemo, useState } from "react";

const ProductList = memo(function ProductList({ products, onSelect }) {
  return (
    <ul>
      {products.map((product) => (
        <li key={product.id}>
          <button type="button" onClick={() => onSelect(product.id)}>
            {product.name}
          </button>
        </li>
      ))}
    </ul>
  );
});

export function Catalog({ products, query }) {
  const [selectedId, setSelectedId] = useState(null);

  const visibleProducts = useMemo(() => {
    const normalizedQuery = query.trim().toLowerCase();

    return products.filter((product) =>
      product.name.toLowerCase().includes(normalizedQuery),
    );
  }, [products, query]);

  const selectProduct = useCallback((productId) => {
    setSelectedId(productId);
  }, []);

  return (
    <div>
      <p>Selected: {selectedId ?? "None"}</p>
      <ProductList products={visibleProducts} onSelect={selectProduct} />
    </div>
  );
}

useMemo caches a calculated value and useCallback caches a function reference while dependencies remain unchanged. memo can skip child rendering when props stay equal. In the catalog, stable list and callback references can avoid rendering the product list when only the selected product changes. [10][11]

If a parent creates a fresh products array every time, the filter cache misses. Profile before adding complexity. React may discard cached values, so correctness must not depend on memoization. React Compiler can reduce the need for manual memoization in projects that enable it.

useDeferredValue and useTransition: render priorities

import { memo, useDeferredValue, useState } from "react";

const SearchResults = memo(function SearchResults({ products, query }) {
  const normalizedQuery = query.trim().toLowerCase();
  const matches = products.filter((product) =>
    product.name.toLowerCase().includes(normalizedQuery),
  );

  return (
    <ul>
      {matches.map((product) => (
        <li key={product.id}>{product.name}</li>
      ))}
    </ul>
  );
});

export function ProductSearch({ products }) {
  const [query, setQuery] = useState("");
  const deferredQuery = useDeferredValue(query);
  const isStale = query !== deferredQuery;

  return (
    <div>
      <label>
        Search products
        <input
          value={query}
          onChange={(event) => setQuery(event.target.value)}
        />
      </label>
      <div aria-busy={isStale}>
        <SearchResults products={products} query={deferredQuery} />
      </div>
    </div>
  );
}

A search field must reflect typing immediately, while expensive results can briefly reflect an older query. useDeferredValue allows React to defer less urgent rendering. Memoizing the results component helps it skip work with unchanged props during urgent updates. [12]

useTransition marks controlled state updates as non-urgent and provides isPending; do not use it for the state controlling a text input. Neither hook guarantees a fixed delay, debounces requests or moves computation to a Web Worker. A costly synchronous filter can still block the main thread. [13]

Custom hooks and useSyncExternalStore

import { useSyncExternalStore } from "react";

function subscribe(onStoreChange) {
  window.addEventListener("online", onStoreChange);
  window.addEventListener("offline", onStoreChange);

  return () => {
    window.removeEventListener("online", onStoreChange);
    window.removeEventListener("offline", onStoreChange);
  };
}

function getSnapshot() {
  return navigator.onLine;
}

function getServerSnapshot() {
  return true;
}

export function useOnlineStatus() {
  return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
}

export function ConnectionStatus() {
  const isOnline = useOnlineStatus();

  return <p role="status">{isOnline ? "Online" : "Offline"}</p>;
}

A custom hook extracts logic that uses hooks, but each call has independent state unless it reads a shared source. For external subscriptions, React provides useSyncExternalStore. The adapter below subscribes to connectivity events, removes listeners on unsubscribe and supplies a state snapshot. [14][15]

Here getServerSnapshot returns a conventional true for SSR and hydration, not a network measurement. navigator.onLine does not guarantee that a specific API is reachable. Other specialized APIs include useLayoutEffect for measurements before paint and, in supported React versions, useEffectEvent for non-reactive effect logic; it must not be used to conceal dependencies. [2][17]

Keep state limited to data that cannot be derived from existing inputs. Use effects to synchronize with external systems, refs for values outside the rendering mechanism, and context for shared values in the component tree. Measure before optimizing. Extract a custom hook when it provides a coherent abstraction, such as a subscription to an external data source.

React React Hooks useState useReducer useEffect useRef useContext useMemo useCallback useDeferredValue Custom Hooks useSyncExternalStore

Frequently asked questions

Does useState update state immediately?

It does not change the current render snapshot. Pass a functional updater when the next value depends on the previous one. [3]

When should I use useEffect?

Use it to synchronize with external resources such as timers, connections or DOM integrations, not to calculate ordinary derived values. [5][6]

Do I always need useMemo and useCallback?

No. They are optimizations, useful when rendering cost or a need for stable references justifies them. [10][11]

Do custom hooks share state?

They share logic, not state automatically. Separate calls can subscribe to the same external source. [14][15]

Sources and references

  1. React Documentation: Rules of Hooks↩
  2. React Documentation: Built-in React Hooks↩
  3. React Documentation: useState↩1↩2↩3
  4. React Documentation: useReducer↩1↩2
  5. React Documentation: useEffect↩1↩2↩3↩4
  6. React Documentation: You Might Not Need an Effect↩1↩2↩3
  7. React Documentation: useRef↩1↩2
  8. React Documentation: useId↩
  9. React Documentation: useContext↩1↩2
  10. React Documentation: useMemo↩1↩2↩3
  11. React Documentation: useCallback↩1↩2
  12. React Documentation: useDeferredValue↩1↩2
  13. React Documentation: useTransition↩1↩2
  14. React Documentation: Reusing Logic with Custom Hooks↩1↩2↩3
  15. React Documentation: useSyncExternalStore↩1↩2
  16. React Documentation: use↩
  17. React Documentation: useEffectEvent↩
  18. React Documentation: rules-of-hooks lint↩

Was this helpful?

Get new articles by email

One short email per new Learning article. No spam, unsubscribe in one click.

We only use your email to send new articles. No third-party sharing.

Back to Learning