useRef vs useState :👈 👉:Fetch Data with useEffect

How to Create Custom Hooks in React

How to Create Custom Hooks in React

1. What Is a Custom Hook in React?

A custom Hook is a JavaScript function that allows you to reuse stateful logic between multiple React components.

React provides built-in Hooks such as useState, useEffect, useRef, and useContext. You can combine these Hooks to create your own reusable Hooks.

For example, suppose multiple components need to:

  • Track a counter.
  • Fetch data from an API.
  • Monitor whether a user is online.
  • Store and retrieve values from local storage.
  • Manage form input values.

Instead of repeating the same logic in every component, you can extract it into a custom Hook and reuse it wherever needed.

Simple definition: A custom Hook is a reusable function that uses React Hooks to share component logic without duplicating the implementation.

2. Why Do We Need Custom Hooks?

Consider two components that need counter functionality. Without a custom Hook, each component must implement its own state and increment/decrement logic.

Without a Custom Hook

import { useState } from "react";
function CounterOne() {
    const [count, setCount] = useState(0);
    return (
        <button onClick={() => setCount(count + 1)}>
            Counter One: {count}
        </button>
    );
}
function CounterTwo() {
    const [count, setCount] = useState(0);
    return (
        <button onClick={() => setCount(count + 1)}>
            Counter Two: {count}
        </button>
    );
}
export { CounterOne, CounterTwo };

Both components repeat similar logic. As the application grows, this duplication can make maintenance more difficult.

With a Custom Hook

You can move the reusable counter logic into a custom Hook and use it in both components.

import { useState } from "react";
function useCounter(initialValue = 0) {
    const [count, setCount] = useState(initialValue);
    function increment() {
        setCount(previous => previous + 1);
    }
    function decrement() {
        setCount(previous => previous - 1);
    }
    function reset() {
        setCount(initialValue);
    }
    return {
        count,
        increment,
        decrement,
        reset
    };
}
export default useCounter;

Now, multiple components can reuse the same counter logic without repeating its implementation.

3. Rules for Creating Custom Hooks

Before creating custom Hooks, understand these important rules.

Rule 1: Start the Name with use

Custom Hook names should start with use, followed by a descriptive name.

Examples:

  • useCounter()
  • useFetch()
  • useLocalStorage()
  • useOnlineStatus()
  • useForm()

Starting the name with use helps React's Hooks lint rules identify functions that follow the Hook conventions.

Rule 2: Call Hooks Only at the Top Level

Call Hooks at the top level of a React component or custom Hook. Do not call them inside conditions, loops, or nested functions.

Incorrect:

function useExample(isEnabled) {
    if (isEnabled) {
        const [value, setValue] = useState(0);
    }
}

Correct:

function useExample(isEnabled) {
    const [value, setValue] = useState(0);
    if (!isEnabled) {
        return null;
    }
    return value;
}

The state Hook is called unconditionally at the top level. The condition controls the returned value, not whether the Hook is called.

Rule 3: Call Custom Hooks Only from React Components or Other Custom Hooks

Do not call custom Hooks from ordinary JavaScript functions that are not React components or custom Hooks.

Incorrect:

function calculateSomething() {
    const [count, setCount] = useState(0);
    return count;
}

Correct:

function useCount() {
    const [count, setCount] = useState(0);
    return { count, setCount };
}
function Counter() {
    const { count, setCount } = useCount();
    return (
        <button onClick={() => setCount(count + 1)}>
            {count}
        </button>
    );
}

Rule 4: Custom Hooks Share Logic, Not Automatically the Same State

Each component calling a custom Hook gets its own independent Hook state.

For example:

function CounterOne() {
    const counter = useCounter(0);
    return (
        <button onClick={counter.increment}>
            Counter One: {counter.count}
        </button>
    );
}
function CounterTwo() {
    const counter = useCounter(10);
    return (
        <button onClick={counter.increment}>
            Counter Two: {counter.count}
        </button>
    );
}

CounterOne starts at 0, while CounterTwo starts at 10. Updating one counter does not update the other.

If multiple components must share the same state, consider React Context, a shared state library, or another appropriate state-management solution.

4. Example 1: Create a Custom Counter Hook

Let's build a reusable counter Hook step by step.

Step 1: Create a Custom Hook File

Create a file named useCounter.js.

import { useState } from "react";
function useCounter(initialValue = 0) {
    const [count, setCount] = useState(initialValue);
    const increment = () => {
        setCount(previous => previous + 1);
    };
    const decrement = () => {
        setCount(previous => previous - 1);
    };
    const reset = () => {
        setCount(initialValue);
    };
    return {
        count,
        increment,
        decrement,
        reset
    };
}
export default useCounter;

Step 2: Use the Custom Hook in a Component

import useCounter from "./useCounter";
function Counter() {
    const {
        count,
        increment,
        decrement,
        reset
    } = useCounter(0);
    return (
        <div>
            <h2>Count: {count}</h2>
            <button onClick={increment}>
                Increment
            </button>
            <button onClick={decrement}>
                Decrement
            </button>
            <button onClick={reset}>
                Reset
            </button>
        </div>
    );
}
export default Counter;

How It Works

  1. useCounter(0) initializes the counter at zero.
  2. The custom Hook maintains the counter's state using useState.
  3. The Hook returns the count and three functions.
  4. The component uses those values and functions to render the UI.
  5. When a function updates the state, React renders the component again with the updated count.

Benefit: The counter logic is reusable, while each component can manage its own independent counter.

5. Example 2: Create a Custom Hook to Fetch API Data

Fetching API data often involves repeating several tasks:

  • Maintaining loading state.
  • Storing the response data.
  • Handling errors.
  • Calling the API when the component mounts or the URL changes.
  • Preventing an outdated request from updating state after the URL changes or the component unmounts.

You can encapsulate this behavior in a custom Hook.

Step 1: Create useFetch.js

import { useEffect, useState } from "react";
function useFetch(url) {
    const [data, setData] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    useEffect(() => {
        const controller = new AbortController();
        async function fetchData() {
            setLoading(true);
            setError(null);
            try {
                const response = await fetch(url, {
                    signal: controller.signal
                });
                if (!response.ok) {
                    throw new Error(
                        `HTTP error: ${response.status}`
                    );
                }
                const result = await response.json();
                setData(result);
            } catch (err) {
                if (err.name !== "AbortError") {
                    setError(err);
                }
            } finally {
                if (!controller.signal.aborted) {
                    setLoading(false);
                }
            }
        }
        fetchData();
        return () => {
            controller.abort();
        };
    }, [url]);
    return { data, loading, error };
}
export default useFetch;

Step 2: Use the Hook in a Component

import useFetch from "./useFetch";
function Users() {
    const {
        data,
        loading,
        error
    } = useFetch("https://jsonplaceholder.typicode.com/users");
    if (loading) {
        return <p>Loading users...</p>;
    }
    if (error) {
        return <p>Error: {error.message}</p>;
    }
    return (
        <div>
            <h2>Users</h2>
            <ul>
                {data.map(user => (
                    <li key={user.id}>
                        {user.name}
                    </li>
                ))}
            </ul>
        </div>
    );
}
export default Users;

How It Works

  1. The component calls useFetch(url).
  2. The custom Hook starts the request in useEffect.
  3. While the request is running, the Hook reports a loading state.
  4. When the response arrives, the Hook stores the data.
  5. If an error occurs, the Hook stores the error.
  6. If the URL changes or the effect is cleaned up, the previous request is aborted when possible.

Important considerations:

  • The example assumes the successful API response contains JSON data.
  • Aborting requests helps prevent unnecessary work and stale updates, but the Hook does not retain old data separately for each URL.
  • For production applications, consider caching, request deduplication, retries, and background revalidation through a data-fetching library such as TanStack Query or SWR.
  • In development, React Strict Mode may run an extra effect setup and cleanup cycle to help detect problems. The effect should therefore be safe to clean up.

6. Example 3: Create a Custom Hook for Local Storage

The browser's local storage allows data to persist across page reloads. A custom Hook can combine React state with local storage so that components can read and update a stored value.

Create useLocalStorage.js

import { useState } from "react";
function useLocalStorage(key, initialValue) {
    const [value, setValue] = useState(() => {
        try {
            const storedValue = window.localStorage.getItem(key);
            return storedValue !== null
                ? JSON.parse(storedValue)
                : initialValue;
        } catch {
            return initialValue;
        }
    });
    function updateValue(newValue) {
        setValue(previous => {
            const nextValue =
                typeof newValue === "function"
                    ? newValue(previous)
                    : newValue;
            try {
                window.localStorage.setItem(
                    key,
                    JSON.stringify(nextValue)
                );
            } catch (error) {
                console.error(
                    "Unable to save to localStorage:",
                    error
                );
            }
            return nextValue;
        });
    }
    return [value, updateValue];
}
export default useLocalStorage;

Use the Hook in a Component

import useLocalStorage from "./useLocalStorage";
function ThemeSettings() {
    const [theme, setTheme] = useLocalStorage(
        "theme",
        "light"
    );
    return (
        <div>
            <p>Current theme: {theme}</p>
            <button
                onClick={() => setTheme("light")}
            >
                Light
            </button>
            <button
                onClick={() => setTheme("dark")}
            >
                Dark
            </button>
        </div>
    );
}
export default ThemeSettings;

Important Limitations

  • This example is intended for browser-only React applications because it accesses window.localStorage.
  • Server-rendered applications need additional care because browser storage is not available during server rendering and initial values must be handled consistently.
  • Changes made by this Hook in one component do not automatically synchronize the state of other component instances using the same key.
  • For cross-component and cross-tab synchronization, a more complete implementation can listen for storage changes or use an appropriate shared-state solution.
  • Do not store passwords, access tokens, or other sensitive information in local storage without carefully considering the security implications.

7. Example 4: Create a Custom Hook for Online Status

The browser provides online and offline events. A custom Hook can listen for those events and expose the current online status to any component that needs it.

import { useEffect, useState } from "react";
function useOnlineStatus() {
    const [isOnline, setIsOnline] = useState(
        () => navigator.onLine
    );
    useEffect(() => {
        function handleOnline() {
            setIsOnline(true);
        }
        function handleOffline() {
            setIsOnline(false);
        }
        window.addEventListener("online", handleOnline);
        window.addEventListener("offline", handleOffline);
        return () => {
            window.removeEventListener(
                "online",
                handleOnline
            );
            window.removeEventListener(
                "offline",
                handleOffline
            );
        };
    }, []);
    return isOnline;
}
export default useOnlineStatus;

Use the Hook

import useOnlineStatus from "./useOnlineStatus";
function NetworkStatus() {
    const isOnline = useOnlineStatus();
    return (
        <p>
            {isOnline
                ? "You are online."
                : "You are offline."}
        </p>
    );
}
export default NetworkStatus;

Note: navigator.onLine indicates the browser's reported network connectivity status. It does not guarantee that your application can reach a particular server or that the internet is fully accessible.

8. Custom Hook vs Regular JavaScript Function

A custom Hook and a regular JavaScript function may both contain reusable logic, but their responsibilities differ.

Feature Custom Hook Regular Function
Can call React Hooks Yes, following the Rules of Hooks No, not as an ordinary function
Can use React state Yes Not directly through Hooks
Can use effects Yes Not directly through Hooks
Typical purpose Reuse stateful React logic Perform calculations or other ordinary operations
Example useCounter() calculateTotal()

Example of a Regular Function

function calculateTotal(price, quantity) {
    return price * quantity;
}

Example of a Custom Hook

import { useState } from "react";
function useCounter() {
    const [count, setCount] = useState(0);
    function increment() {
        setCount(previous => previous + 1);
    }
    return { count, increment };
}

Use a regular function for reusable calculations that do not require React Hooks. Use a custom Hook when you need to reuse logic involving React state, effects, context, or other Hooks.

9. Custom Hook vs React Component

Feature Custom Hook React Component
Purpose Reuses logic Renders UI
Naming convention Starts with use Usually starts with an uppercase letter
Returns Values, objects, arrays, or functions React elements or other valid renderable results
Used in JSX as an element No Yes
Example const counter = useCounter(); <Counter />

A custom Hook does not render a UI component by itself. It provides logic and values that a component can use to render its UI.

10. How to Organize Custom Hooks in a React Project

For a small application, you can keep custom Hooks in a dedicated folder. For example:

src/
├── components/
│   ├── Counter.jsx
│   ├── Users.jsx
│   └── NetworkStatus.jsx
│
├── hooks/
│   ├── useCounter.js
│   ├── useFetch.js
│   ├── useLocalStorage.js
│   └── useOnlineStatus.js
│
├── App.jsx
└── main.jsx

This structure separates reusable logic from UI components. As the application grows, you can organize Hooks by feature or domain instead of putting every Hook into one folder.

11. Common Mistakes When Creating Custom Hooks

Mistake 1: Forgetting the use Prefix

Prefer names such as useCounter and useFetch for functions that use React Hooks. This helps React's lint rules recognize Hook usage.

Mistake 2: Calling Hooks Conditionally

Do not place Hook calls inside if statements, loops, or nested functions. Keep Hook calls at the top level of the custom Hook or component.

Mistake 3: Forgetting Effect Dependencies

If an effect depends on a URL, identifier, or other reactive value, include that value in the dependency array. Missing dependencies can cause stale values or incorrect behavior.

Mistake 4: Forgetting Cleanup

Effects that subscribe to events, create timers, or manage external resources should clean them up when the effect is re-run or the component unmounts.

Mistake 5: Expecting State to Be Shared Automatically

Calling the same custom Hook in two components normally creates two independent sets of state. A custom Hook shares logic, not a single state instance.

Mistake 6: Creating Custom Hooks for Everything

Not every repeated function needs a custom Hook. A simple calculation or formatting operation may be better as a regular JavaScript function. Create a custom Hook when it meaningfully encapsulates reusable React logic.

12. Best Practices for Custom Hooks

  • Use descriptive names: Name Hooks according to their responsibility, such as useAuth, useDebounce, or useOnlineStatus.
  • Keep each Hook focused: Prefer one clear responsibility instead of combining unrelated behavior.
  • Accept parameters: Make Hooks reusable by accepting values such as URLs, initial values, or configuration options.
  • Return a clear interface: Return only the data and functions consumers need. An object is useful when the Hook returns several named values; an array can work well for a state-and-setter pair.
  • Handle errors: Define appropriate error behavior for network requests, storage operations, and external APIs.
  • Clean up resources: Remove event listeners, clear timers, and cancel supported requests when appropriate.
  • Follow the Rules of Hooks: Call Hooks at the top level and only from React components or custom Hooks.
  • Avoid unnecessary abstraction: Extract logic when reuse or clearer separation makes the code easier to maintain.
  • Test independently: Verify initial values, state changes, error handling, and cleanup behavior.
  • Use established libraries when appropriate: Data fetching, form management, and complex shared state may be better handled by dedicated libraries than by custom implementations.

13. Interview Questions and Answers

Q1. What is a custom Hook in React?

A custom Hook is a JavaScript function whose name starts with use and that can use React Hooks to encapsulate and reuse stateful logic between components.

Q2. Why do we create custom Hooks?

Custom Hooks reduce duplicated logic, improve maintainability, and separate reusable behavior from UI rendering.

Q3. Can a custom Hook use useState and useEffect?

Yes. A custom Hook can use built-in Hooks such as useState, useEffect, useRef, and other custom Hooks, provided the Rules of Hooks are followed.

Q4. Do two components share state when they call the same custom Hook?

No, not by default. Each component calling the Hook gets its own independent state. Shared state requires an appropriate shared-state mechanism, such as Context or a state-management library.

Q5. Can a custom Hook return multiple values?

Yes. It can return an object, array, function, or another JavaScript value. Choose a return structure that makes the Hook easy to use.

Q6. What is the difference between a custom Hook and a component?

A component is responsible for rendering UI, while a custom Hook encapsulates reusable React logic and returns values or functions for components to use.

Q7. Can a custom Hook be asynchronous?

A custom Hook can manage asynchronous operations, such as API requests, using effects, state, or suitable libraries. However, a function that directly calls Hooks should not itself be declared async, because that would make it return a Promise rather than the synchronous values expected from a Hook call.

Q8. When should you not create a custom Hook?

A custom Hook is unnecessary when the logic is a simple calculation that does not use React Hooks and does not benefit from additional abstraction. A regular JavaScript function is often more appropriate in that situation.

14. Summary

Concept Explanation
Custom Hook A function for reusing React logic between components.
Naming Names should start with use.
State management Custom Hooks can use useState to manage local state.
Side effects Custom Hooks can use useEffect to manage synchronization with external systems.
Reusability Multiple components can reuse the same logic.
State sharing State is independent per Hook call unless an explicit shared-state mechanism is used.
Rules Follow the Rules of Hooks and keep Hook calls at the top level.

Final takeaway: Custom Hooks let you extract reusable React logic into focused functions. Start by identifying repeated behavior, move that behavior into a function whose name begins with use, return a clear set of values or functions, and use the Hook in the components that need it. This makes React applications easier to maintain, test, and extend.

🔙
useRef vs useState :👈 👉:Fetch Data with useEffect

Comments and Discussion