# Understanding and Building React Custom Hooks: A Practical Guide

> *Originally published on Medium (Becoming For Better). [Read on Medium for free via Friend Link](https://medium.com/becoming-for-better/understanding-and-building-react-custom-hooks-a-practical-guide-037ad33d1cd1?source=friends_link&sk=836db934d8770a02019134bb1c213806).*
>
> ⚡ **[Get the Production-Ready React Hooks Pack](https://www.buymeacoffee.com/mkare/e/599267)**

> **Quick Takeaways**
> - **Hook Rules First** : Start with `use`, compose built-in hooks, stay reusable, and never return JSX.
> - **10 Production Patterns** : Copy-ready hooks for focus, delays, window size, outside clicks, forms, fetching, debouncing, storage, media queries, and toggles.
> - **Build vs. Borrow** : Know when to write lightweight custom hooks and when to reach for `usehooks.com` or `usehooks-ts.com`.

* * *

Custom hooks in React are a powerful tool for reducing code duplication, improving code organization, and boosting overall productivity. In this article, we’ll explore what custom hooks are, how to build them, and walk through ten practical examples.

![Diagram illustrating React Custom Hooks encapsulating reusable state and side-effect logic across components](https://miro.medium.com/v2/resize:fit:700/1*-hF_0wuTbbgAMQyXibsmBQ.png)
*React custom hooks extract shared stateful logic out of UI components into clean, reusable functions.*

### What is a Custom Hook?

A custom hook is a JavaScript function that uses one or more built-in React hooks to encapsulate reusable logic. Think of it as extracting the engine out of a component so any other component can drop it in without duplicating wiring.

### Rules for Creating Custom Hooks

Here are the core principles to keep in mind when creating a custom hook:

* **Naming Convention** : Always start the hook name with `use`. For example, a hook for managing form input can be named `useFormInput`.
* **Dependencies** : You can use built-in hooks like `useState`, `useEffect`, or even other custom hooks within your own.
* **Reusability** : A custom hook should be reusable in different components without modification.
* **No JSX** : Custom hooks should contain logic only. They must not return JSX or manage rendering directly.

* * *

### Useful Custom Hook Examples

#### 1. `useFocus`

This hook helps programmatically focus a DOM element using `useRef` and `useCallback`.

```jsx
import { useRef, useCallback } from "react";

export const useFocus = () => {
  const ref = useRef(null);

  const focusElement = useCallback(() => {
    if (ref.current) {
      ref.current.focus();
    }
  }, []);

  return [ref, focusElement];
};
```

* * *

#### 2. `useDelay`

Returns `true` after a specified delay — useful for loading spinners or delayed content.

```jsx
import { useState, useEffect } from "react";

export const useDelay = (delayTime) => {
  const [done, setDone] = useState(false);

  useEffect(() => {
    const delay = setTimeout(() => {
      setDone(true);
    }, delayTime);

    return () => clearTimeout(delay);
  }, [delayTime]);

  return done;
};
```

* * *

#### 3. `useWindowSize`

Tracks window dimensions — perfect for responsive layouts.

```jsx
import { useState, useEffect } from "react";

export const useWindowSize = () => {
  const [windowSize, setWindowSize] = useState({
    width: window.innerWidth,
    height: window.innerHeight,
  });

  useEffect(() => {
    const handleResize = () => {
      setWindowSize({
        width: window.innerWidth,
        height: window.innerHeight,
      });
    };

    window.addEventListener("resize", handleResize);

    return () => {
      window.removeEventListener("resize", handleResize);
    };
  }, []);

  return windowSize;
};
```

* * *

#### 4. `useOnClickOutside`

Detects clicks outside a specified element — great for modals and dropdowns.

```jsx
import { useEffect } from "react";

export const useOnClickOutside = (ref, handler) => {
  useEffect(() => {
    const listener = (event) => {
      if (!ref.current || ref.current.contains(event.target)) {
        return;
      }
      handler(event);
    };

    document.addEventListener("mousedown", listener);
    return () => {
      document.removeEventListener("mousedown", listener);
    };
  }, [ref, handler]);
};
```

* * *

#### 5. `useFormUpdate`

Warns users about unsaved changes before leaving the page.

```jsx
import React, { useState, useEffect } from "react";

export const useFormUpdate = () => {
  const [isFormUpdated, setIsFormUpdated] = useState(false);

  useEffect(() => {
    const handleBeforeUnload = (event) => {
      if (isFormUpdated) {
        const message =
          "You have unsaved changes. " +
          "Are you sure you want to leave?";
        event.returnValue = message;
        return message;
      }
    };

    window.addEventListener(
      "beforeunload",
      handleBeforeUnload
    );

    return () => {
      window.removeEventListener(
        "beforeunload",
        handleBeforeUnload
      );
    };
  }, [isFormUpdated]);

  const handleFormUpdate = () => {
    setIsFormUpdated(true);
  };

  useEffect(() => {
    const selector =
      "form input, form select, form textarea";
    const formElements = document.querySelectorAll(selector);
    const handleFieldChange = () => {
      setIsFormUpdated(true);
    };

    formElements.forEach((element) => {
      element.addEventListener("change", handleFieldChange);
    });

    return () => {
      formElements.forEach((element) => {
        element.removeEventListener(
          "change",
          handleFieldChange
        );
      });
    };
  }, []);

  return handleFormUpdate;
};
```

* * *

#### 6. `useFetch`

Simplifies fetching and managing API data.

```jsx
import React, { useState, useEffect } from "react";

export const useFetch = (url) => {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch(url);
        if (!response.ok) {
          throw new Error("Network response was not ok");
        }
        const result = await response.json();
        setData(result);
      } catch (error) {
        setError(error);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [url]);

  return { data, loading, error };
};
```

* * *

#### 7. `useDebounce`

Delays input updates — useful for search boxes and reducing API calls.

```jsx
import React, { useState, useEffect } from "react";

export const useDebounce = (value, delay) => {
  const [debouncedValue, setDebouncedValue] = useState(value);

  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedValue(value);
    }, delay);

    return () => {
      clearTimeout(handler);
    };
  }, [value, delay]);

  return debouncedValue;
};
```

* * *

#### 8. `useLocalStorage`

Persistent storage for data between sessions.

```jsx
import React, { useState, useEffect } from "react";

export const useLocalStorage = (key, initialValue) => {
  const [storedValue, setStoredValue] = useState(() => {
    try {
      const item = window.localStorage.getItem(key);
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      console.error(error);
      return initialValue;
    }
  });

  const setValue = (value) => {
    try {
      const valueToStore =
        value instanceof Function
          ? value(storedValue)
          : value;
      setStoredValue(valueToStore);
      window.localStorage.setItem(
        key,
        JSON.stringify(valueToStore)
      );
    } catch (error) {
      console.error(error);
    }
  };

  useEffect(() => {
    const handleStorageChange = () => {
      try {
        const item = window.localStorage.getItem(key);
        setStoredValue(
          item ? JSON.parse(item) : initialValue
        );
      } catch (error) {
        console.error(error);
      }
    };

    window.addEventListener("storage", handleStorageChange);

    return () => {
      window.removeEventListener(
        "storage",
        handleStorageChange
      );
    };
  }, [key, initialValue]);

  return [storedValue, setValue];
};
```

* * *

#### 9. `useMediaQuery`

Handles responsive rendering based on screen size.

```jsx
import React, { useState, useEffect } from "react";

export const useMediaQuery = (query) => {
  const [matches, setMatches] = useState(false);

  useEffect(() => {
    const mediaQuery = window.matchMedia(query);

    const handleMediaQueryChange = (event) => {
      setMatches(event.matches);
    };

    mediaQuery.addListener(handleMediaQueryChange);
    setMatches(mediaQuery.matches);

    return () => {
      mediaQuery.removeListener(handleMediaQueryChange);
    };
  }, [query]);

  return matches;
};
```

* * *

#### 10. `useToggle`

Quick toggle between true/false states — ideal for toggles and switches.

```jsx
import React, { useState } from "react";

export const useToggle = (defaultValue) => {
  const [value, setValue] = useState(defaultValue);

  function toggleValue(value) {
    setValue((currentValue) =>
      typeof value === "boolean" ? value : !currentValue
    );
  }

  return [value, toggleValue];
};
```

* * *

### Bonus: Custom Hook Libraries

Instead of building every hook from scratch, you can take advantage of excellent open-source libraries:

* [**usehooks.com**](https://usehooks.com) : A treasure trove of custom hooks with examples and explanations.
* [**usehooks-ts.com**](https://usehooks-ts.com) : Lightweight, type-safe, and written in TypeScript. Great for advanced usage.

### Benefits of Using Hook Libraries

* **Save time** : Ready-made, battle-tested solutions for common UI state.
* **Reduce repetition** : Eliminate boilerplate across components.
* **Better documentation** : Learn edge-case handling from real-world examples.

* * *

Which custom hook do you find yourself copying into every new React project — or which built-in pattern still trips up your team? I'd love to hear your thoughts 🧠💬

* * *

### Keep Exploring

If you want to level up your frontend architecture and developer tooling, check out these related deep-dives:

* **[Taming Claude Code: A Guide to CLAUDE.md and Hooks](https://javascript.plainenglish.io/taming-claude-code-a-guide-to-claude-md-and-hooks-ed059879991c)** — *Structure AI coding workflows with deterministic project rules and lifecycle hooks.*
* **[How Game Physics Works: Building a 2D Physics Engine from Scratch in Canvas](https://javascript.plainenglish.io/how-game-physics-works-building-a-2d-physics-engine-from-scratch-in-canvas-5cd26416ddb8)** — *A hands-on breakdown of simulation loops, collisions, and browser rendering.*

* * *

### About the Author

I'm **Mustafa Morbel** — Senior Frontend Engineer with over 17 years of experience crafting high-performance React architectures, WebGL applications, and developer tooling.

* Find full component examples and open-source boilerplates on my **[GitHub (@mkare)](https://github.com/mkare)**.
* Connect on **[LinkedIn](https://linkedin.com/in/mustafamorbel)** and follow along on **[X / Twitter (@mustafamorbel)](https://x.com/mustafamorbel)** for React & TypeScript best practices.
* Have a custom hook you use in every project? Share it in the comments below, and leave a few claps if you found this guide helpful!
