Thuta Learning
React
IntermediateWeb DevelopmentIntermediate

Custom Hooks

ReactLesson 1630 min

What you'll walk away with

  • Extract duplicated useState + useEffect logic from two components into one custom hook
  • Explain that a custom hook shares logic, not state
  • Understand why hooks may only be called at the top level of a component or another hook
  • Write the dependencies and cleanup of an effect inside a hook so they match its arguments

Explain it simply

Custom hooks in plain language

A custom hook is an ordinary JavaScript function whose name starts with use and that calls other hooks such as useState and useEffect inside it. When two or three components need the same logic, such as tracking the window width or checking whether the user is online, you write it once in a hook instead of copying it around.

Think of a recipe. Two cooks follow the same recipe but cook in two separate pots. A custom hook works the same way: every component that calls it gets the same procedure, but its own private state.

Problem → Why → Solution

The problem: copied logic slowly drifts apart

StatusBar shows 'Online' or 'Offline', and SaveButton must be disabled while offline. The first component got both listeners and a careful cleanup; the second was copied in a hurry and lost its cleanup. Every time SaveButton mounts and unmounts, listeners pile up and keep calling the setter of a component that is already gone.

Duplicated.jsx
function StatusBar() {
  const [isOnline, setIsOnline] = useState(navigator.onLine);
  useEffect(() => {
    const on = () => setIsOnline(true);
    const off = () => setIsOnline(false);
    window.addEventListener('online', on);
    window.addEventListener('offline', off);
    return () => {
      window.removeEventListener('online', on);
      window.removeEventListener('offline', off);
    };
  }, []);
  return <p>{isOnline ? 'Online' : 'Offline'}</p>;
}

function SaveButton() {
  const [isOnline, setIsOnline] = useState(navigator.onLine);
  useEffect(() => {
    window.addEventListener('online', () => setIsOnline(true));
    window.addEventListener('offline', () => setIsOnline(false));
    // copied in a hurry: no cleanup, listeners pile up
  }, []);
  return <button disabled={!isOnline}>Save</button>;
}

Why copy-paste is risky here

Each copy becomes one more place to fix bugs. A fix made in the first copy tends to be missing from the second, and as components multiply nobody knows which version is right. A custom hook keeps the logic in one place: write the cleanup correctly once and every component that uses it is correct.

Core concept: share logic, not state

There is no magic inside a custom hook. When a component calls useWindowWidth(), the useState and useEffect inside the hook behave exactly as if the component had called them itself. So when two components call the same hook, they get two separate states, two effects and two listeners. To really share one value between components, you still lift state up to a parent or use context.

You decide what the hook returns. For a single value such as a width, return it directly. For a value plus an action, return an array like useState's [value, setValue], which lets callers pick their own names. With three or four pieces, an object such as { data, error, isLoading } reads better. Hooks can take arguments too, but every argument used inside an effect must appear in its dependency array.

There are two Rules of Hooks: call hooks only at the top level of a component or another hook (never after an if, inside a loop or after an early return), and never from a plain JavaScript function. React tracks a component's hook state by call order, not by name, so skipping one hook in one render shifts every later piece of state into the wrong slot. The use prefix is the convention that lets eslint-plugin-react-hooks recognise a hook and check these rules for you.

When should you extract a hook? When the same pairing of state and effect repeats in two or more components, or when even a single component would read better if a name described what a block of logic does. A name like useOnlineStatus states the purpose more clearly than five lines of useEffect. Do not turn a helper that calls no hooks into a hook.

A hook call is code pasted into the component
  1. Component calls useX() at top level
  2. The hook's state and effects run there
  3. Each component gets private state
  4. Hook returns a value; the UI uses it

If a function calls no hooks at all, it is not a hook: give it a normal name without use.

General pattern

jsx
function useSomething(arg) {
  const [value, setValue] = useState(initialValue);
  useEffect(() => {
    // subscribe or start work that depends on arg
    return () => { /* undo it */ };
  }, [arg]);
  return value; // or [value, action] or { value, action }
}

function SomeComponent() {
  const value = useSomething(arg); // top level only, never inside if/loops
}

Name it with use, call other hooks inside, list the arguments the effect uses as dependencies, and return only what the component needs.

Worked example: useWindowWidth

The hook below keeps the browser window's width in state and updates it on every resize event. The App component knows nothing about resize listeners; it calls the hook and shows the number it gets back.

A note on server rendering

useState(window.innerWidth) reads window while rendering. That is fine in a browser-only app built with Vite, but in frameworks that render on the server there is no window and it crashes. In such apps, start from a fallback value and read window inside the effect.

jsx
import { useEffect, useState } from 'react';

function useWindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);

  useEffect(() => {
    function handleResize() {
      setWidth(window.innerWidth);
    }

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  return width;
}

function App() {
  const width = useWindowWidth();
  return <p>Window width is {width}px</p>;
}

Code breakdown

  1. A function named use...function useWindowWidth() {

    The use prefix tells React tooling and the linter that this is a hook. Otherwise it is an ordinary function.

  2. State owned by the callerconst [width, setWidth] = useState(window.innerWidth);

    This state belongs to whichever component calls the hook. Two calling components mean two independent width states.

  3. Subscribe oncewindow.addEventListener('resize', handleResize);

    With an empty dependency array the listener is added once, when the component mounts. Every resize calls setWidth, which triggers a re-render.

  4. Clean upreturn () => window.removeEventListener('resize', handleResize);

    The listener is removed when the component unmounts, and also during Strict Mode's test remount in development. It must be the same function reference, which is why handleResize has a name.

  5. Use it like a built-in hookconst width = useWindowWidth();

    App calls the hook at its top level and receives a number. All the listener details stay hidden inside the hook.

You should see
Rendering App shows one line such as 'Window width is 1280px' (the number depends on your window). The number updates every time you resize the window.

Fixing the problem with one hook

Rewriting the two components from the problem section around one useOnlineStatus hook leaves a single correct version, cleanup included. Each component receives just an isOnline boolean and draws its own UI.

useOnlineStatus.jsx
function useOnlineStatus() {
  const [isOnline, setIsOnline] = useState(navigator.onLine);
  useEffect(() => {
    const goOnline = () => setIsOnline(true);
    const goOffline = () => setIsOnline(false);
    window.addEventListener('online', goOnline);
    window.addEventListener('offline', goOffline);
    return () => {
      window.removeEventListener('online', goOnline);
      window.removeEventListener('offline', goOffline);
    };
  }, []);
  return isOnline;
}

function StatusBar() {
  const isOnline = useOnlineStatus();
  return <p>{isOnline ? 'Online' : 'Offline'}</p>;
}

function SaveButton() {
  const isOnline = useOnlineStatus();
  return <button disabled={!isOnline}>{isOnline ? 'Save' : 'Reconnecting…'}</button>;
}

For hooks that subscribe to an external value in the browser, React also has a built-in hook called useSyncExternalStore. Once the useState + useEffect shape in this lesson makes sense, look it up in the React docs.

In real projects

Custom hooks in real projects

Open the src/hooks folder of a medium-sized React project and you will usually find hooks like the ones below. They all share one shape: hide the messy contact with the browser or the network, and hand the component one simple value.

  • useDebouncedValue: update a search value only after typing pauses, instead of sending a request on every keystroke.
  • useLocalStorage: tie state to localStorage so a theme or a draft survives a page refresh.
  • useMediaQuery: return a boolean for whether a CSS media query matches, so mobile and desktop layouts can differ.
  • useFetch or useUser: manage data, error and loading in one place; larger projects often use hooks from a library such as TanStack Query instead.

Because hooks are plain functions they are also easy to test: tools such as Testing Library's renderHook let you exercise one hook on its own, without any UI.

Common mistakes

Common mistakes with custom hooks

Calling a hook inside a condition

With if (showWidth) { const width = useWindowWidth(); }, the number of hook calls changes in the render where showWidth flips, and React fails with an error such as 'Rendered more hooks than during the previous render'. Always call the hook at the top level and apply the condition to the value it returns.

Expecting a hook to share state between components

Call useCart() in both Header and ProductPage, add an item on ProductPage, and the Header count does not move: there are two separate cart states. To share one value, keep the state in a context provider and let the hook read it with useContext.

Leaving a hook argument out of the dependencies

If the effect inside useFetch(url) declares [], it fetches only the first url and keeps showing old data after the url changes. Put every argument the effect uses, here [url], in the dependency array.

Mini challenge

Mini challenge: useDebouncedValue

A search page should not search on every keystroke. Write a useDebouncedValue(value, delayMs) hook that returns the value only after the user has stopped typing for delayMs, and use it in a SearchPage.

  • The hook keeps the debounced value in state, starting from the value passed in
  • An effect delays the update with setTimeout and calls clearTimeout in its cleanup
  • The dependency array includes both value and delayMs
  • SearchPage shows 'Typing: ...' and 'Searching for: ...' separately
SearchPage.jsx
import { useEffect, useState } from 'react';

function useDebouncedValue(value, delayMs) {
  // TODO: state for the debounced value
  // TODO: effect that waits delayMs, then copies value into that state
  // TODO: cleanup that cancels the pending timer
  // TODO: return the debounced value
}

export default function SearchPage() {
  // TODO: query state for the input, then call useDebouncedValue(query, 300)
  return null; // TODO: input + "Typing:" line + "Searching for:" line
}

Expected: Typing 'rea' quickly shows Typing: rea at once while Searching for: stays empty. After a 300 ms pause it becomes Searching for: rea, and only one timer ever completes.

Show hint

The cleanup is the key: each new keystroke changes value, React runs the old effect's cleanup first, so the old timer is cancelled and only the last one survives.

Show solution
SearchPage.jsx
import { useEffect, useState } from 'react';

function useDebouncedValue(value, delayMs) {
  const [debounced, setDebounced] = useState(value);

  useEffect(() => {
    const id = setTimeout(() => setDebounced(value), delayMs);
    return () => clearTimeout(id); // a newer value cancels the old timer
  }, [value, delayMs]);

  return debounced;
}

export default function SearchPage() {
  const [query, setQuery] = useState('');
  const debouncedQuery = useDebouncedValue(query, 300);

  return (
    <>
      <input
        aria-label="Search"
        value={query}
        onChange={(e) => setQuery(e.target.value)}
      />
      <p>Typing: {query}</p>
      <p>Searching for: {debouncedQuery}</p>
    </>
  );
}

Quick quiz 1 / 3

Both Sidebar and Header call useWindowWidth(). What happens?

Quick quiz 2 / 3

What is wrong here? function Banner({ compact }) { if (compact) return null; const width = useWindowWidth(); return <p>{width}</p>; }

Quick quiz 3 / 3

Which function should be written as a custom hook (named use...)?

What to remember

  • A custom hook is an ordinary function whose name starts with use and that calls other hooks
  • Hooks share logic; every calling component gets its own state and effects
  • Call hooks only at the top level of a component or hook, never after if, loops or early returns
  • List the hook's arguments as effect dependencies and never forget the cleanup

React Documentation — React

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Custom Hooks | Thuta Learning