Create a custom hook in React

Encapsulate reusable logic into custom hooks to simplify your React components.

advancedAdvanced hooks and patternsreactcustom hookreuse logichooks
Published: 10/26/2025
Updated: 10/26/2025

Question

Create a custom hook in React.


Answer

Custom hooks allow you to reuse stateful logic across components.

Example — useFetch hook:

import { useEffect, useState } from 'react';

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

  useEffect(() => {
    async function getData() {
      const res = await fetch(url);
      const json = await res.json();
      setData(json);
      setLoading(false);
    }
    getData();
  }, [url]);

  return { data, loading };
}
function Users() {
  const { data, loading } = useFetch(
    'https://jsonplaceholder.typicode.com/users'
  );

  if (loading) return <p>Loading...</p>;
  return (
    <ul>
      {data.map((u) => (
        <li key={u.id}>{u.name}</li>
      ))}
    </ul>
  );
}

✅ Any component can now reuse the same fetching logic.

Real-World Example

  • useDebounce
  • useLocalStorage
  • useMediaQuery

Quick Practice

Create a useWindowSize hook that returns current window width and height.

Summary

Custom hooks abstract repetitive logic and make React components cleaner and more reusable.

Related Videos
Watch these videos to learn more about this topic
Frequently Asked Questions

When should I create a custom hook?

When multiple components share the same logic like fetching, form handling, or animation.


Stay Updated

Get the latest frontend challenges, interview questions and tutorials delivered to your inbox.