#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Custom React Hooks

What are Custom Hooks?

A custom hook is a JavaScript function whose name starts with use and which calls other hooks, such as useState or useEffect, to package a piece of reusable logic. You write one when two or more components need the same stateful behaviour, for example fetching data, tracking window size, or reading from local storage.

The problem they solve

Imagine two components that both load data from an API. Each needs a data state, a loading flag, an error state, and a useEffect that calls fetch. Without custom hooks, you copy those twenty lines into both components. When you later fix a bug, you have to fix it twice.

Regular helper functions cannot fix this, because ordinary functions are not allowed to call hooks. A custom hook is the official way to extract hook-based logic into one place.

import { useState, useEffect } from 'react';

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

  useEffect(() => {
    let ignore = false;
    setLoading(true);
    fetch(url)
      .then((res) => {
        if (!res.ok) throw new Error('Request failed: ' + res.status);
        return res.json();
      })
      .then((json) => { if (!ignore) setData(json); })
      .catch((err) => { if (!ignore) setError(err); })
      .finally(() => { if (!ignore) setLoading(false); });
    return () => { ignore = true; };
  }, [url]);

  return { data, loading, error };
}

function UserList() {
  const { data, loading, error } = useFetch('/api/users');
  if (loading) return <p>Loading...</p>;
  if (error) return <p>{error.message}</p>;
  return <ul>{data.map((u) => <li key={u.id}>{u.name}</li>)}</ul>;
}

Logic is shared, state is not

This is the point that surprises most people. If UserList and PostList both call useFetch, they do not share one data variable. Each call gets its own separate state, exactly as if each component had written the useState calls itself. A custom hook reuses the recipe, not the result.

If you need several components to see the same live value, that is a job for lifting state up or using Context, which can itself be wrapped in a custom hook like useAuth().

Rules a custom hook must follow

  • The name starts with "use". React's lint rules rely on this prefix to check that hooks are used correctly inside it.
  • Call hooks at the top level only. Not inside conditions, loops or nested functions, so the order of hook calls stays the same on every render.
  • Call it only from components or other hooks. Calling useFetch from an event handler or a plain utility function will throw.

A mistake to avoid: a hook that is not really a hook

Some beginners name every helper useSomething, even when it calls no hooks at all, such as a function that formats a date. That adds the hook rules to a function that does not need them and confuses readers. If a function does not use any hooks inside, make it a normal function with a normal name.

The opposite mistake also happens: putting the fetch call in a custom hook but forgetting to list url in the effect's dependency array. The hook then ignores new URLs and keeps showing old data.

Good candidates for custom hooks

  • useFetch or useHttp for loading and sending data.
  • useInput for a form field's value, touched state and validation.
  • useLocalStorage to keep a value in sync with storage.
  • useDebounce to delay a search query until typing pauses.

Rule of thumb: when you see the same group of hooks copied into a second component, pull it into a use function and return just what the components need.

Ready to master real-world web development?

Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.

Explore Course