Open In App

How To Create a Custom Hook in React?

Last Updated : 02 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In web application development, developers often need to reuse logic multiple times, which can become difficult to manage manually. So, the custom hook can be used to solve the problem of reusing complex stateful logic across multiple components.

What are Custom Hooks?

Custom Hooks are special functions that we create in our application to extract certain functionalities and increase reusability. These hooks are just regular JavaScript functions that begin with the prefix "use".

  • Custom Hooks provide code reusability features.
  • It is easier to debug and modify the logic.
  • Unlike traditional functions, custom hooks can maintain state using React’s built-in hooks.

To read more about custom hook prefer this article - Custom Hook

How to Create a Custom Hook in React?

Creating a custom hook in React is fairly straightforward. Let’s break it down with an example.

Steps to Create a Custom Hook

  • Use React's Built-in Hooks: Inside your custom hook, you can use any of React’s built-in hooks (useState, useEffect, etc.).
  • Return a Value: Return values from your custom hook, typically the state or functions that you want to share.
  • Start with 'use': Name your custom hook starting with use, for example, useFetchData, useLocalStorage, etc.

Implementing the Custom Hook

Create the React app

npx create-react-app react-app
cd react-app

Now, create the components and the hooks folder in the src folder.

Folder Structure

Output CSS
/*src/index.css*/
body {
    font-family: Arial, sans-serif;
    background-color: #f5f5f5;
    text-align: center;
}
JavaScript
// src/components/CounterComponent.js

import React from "react";
import useCounter from "../hooks/useCounter";

const CounterComponent = () => {
    const { count, increment, decrement, reset } = useCounter(0);

    return (
        <div style={{ textAlign: "center", padding: "20px" }}>
            <h2>Counter: {count}</h2>
            <button onClick={increment}>Increase</button>
            <button onClick={decrement}>Decrease</button>
            <button onClick={reset}>Reset</button>
        </div>
    );
};

export default CounterComponent;
JavaScript
//src/App.js

import React from "react";
import CounterComponent from "./components/CounterComponent";
import "./index.css"; //

const App = () => {
    return (
        <div>
            <h1>React Custom Hooks Example</h1>
            <CounterComponent />
        </div>
    );
};

export default App;
JavaScript
//src/hooks/useCounter.js

import { useState } from "react";

const useCounter = (initialValue = 0) => {
    const [count, setCount] = useState(initialValue);

    const increment = () => setCount(count + 1);
    const decrement = () => setCount(count - 1);
    const reset = () => setCount(initialValue);

    return { count, increment, decrement, reset };
};

export default useCounter;

Output

In this example

  • Creates a custom hook (useCounter.js) to manage a counter.
  • Uses this custom hook inside a component (CounterComponent.js).
  • Integrates the component into App.js to display it on the webpage.
  • Allows users to increment, decrement, and reset the counter.

Best Practices for Creating Custom Hooks

  • Keep Logic Separate: Custom hooks should only contain logic, and UI-related code (such as JSX) should remain in the components. This ensures that your hooks remain reusable and focused.
  • Descriptive Names: Name your custom hooks with a "use" prefix to follow React's conventions and make it clear that the function is a hook (e.g., useFetchData, useLocalStorage).
  • Avoid Side Effects in the Hook: If your custom hook has side effects, ensure that they are properly managed (e.g., using useEffect or returning functions to clean up side effects).
  • Encapsulate Reusable Logic: When you notice similar logic repeated across components, consider extracting it into a custom hook to reduce duplication and improve maintainability.

When to Use Custom Hooks?

  • When multiple components share the same logic (e.g., fetching data, managing state).
  • When you want to keep component logic clean and reusable.
  • When using third-party APIs that need custom handling.
  • When abstracting complex logic into reusable functions.

Next Article

Similar Reads