Popular Searches
Popular Course Categories
Popular Courses

Custom Hooks

Custom Hooks

Advanced React Hooks

Custom Hooks in React JS – Complete Detailed Notes

Custom Hooks are an important feature of React JS that allow developers to reuse stateful logic between multiple functional components. They help make applications more organized, maintainable, reusable, and easier to test.

React provides built-in Hooks such as useState, useEffect, useContext, useMemo, and useCallback. When application requirements need reusable logic beyond these built-in Hooks, developers can create their own Custom Hooks.

1. What Are Custom Hooks?

A Custom Hook is a JavaScript function that uses one or more React Hooks to encapsulate reusable logic. It allows multiple components to use the same logic without repeatedly writing the same implementation.

For example, suppose two components need to track a counter. Instead of writing the counter state and update logic separately in both components, we can create a Custom Hook named useCounter and reuse it wherever required.

Definition

A Custom Hook is a reusable function whose name begins with use followed by a capital letter and that can call other Hooks at the top level of its function.

Why Are Custom Hooks Used?

  • To reuse stateful logic across multiple components.
  • To reduce repeated code and improve maintainability.
  • To separate business logic from the user interface.
  • To organize complex component logic into smaller functions.
  • To make components easier to understand and test.
  • To reuse functionality such as form handling, counters, data fetching, online status, and local storage.

2. Custom Hooks vs Built-in Hooks

Feature Built-in Hooks Custom Hooks
Definition Hooks provided by React. Hooks created by developers.
Examples useState, useEffect, useContext useCounter, useForm, useFetch
Purpose Provide React features. Combine and reuse logic for application-specific tasks.
Customization Used according to React's API. Designed according to application requirements.
Can use other Hooks? Built-in Hooks provide React functionality. Yes, Custom Hooks can call built-in Hooks and other Custom Hooks.

3. Rules for Creating Custom Hooks

Custom Hooks follow the Rules of Hooks. These rules help React correctly track state and other Hook features between renders.

  • Start the name with use: Use names such as useCounter, useForm, and useFetch.
  • Use camelCase: Begin with lowercase use, followed by a capital letter for the descriptive part.
  • Call Hooks at the top level: Do not call Hooks inside conditions, loops, or nested functions.
  • Call Hooks only from React functions: Use them inside function components or other Custom Hooks, not ordinary JavaScript functions.
  • Return useful data or functions: A Custom Hook may return a value, an object, an array, or functions.
  • Keep logic focused: Give each Custom Hook a clear responsibility.
  • Include correct dependencies: When using Effects or memoization Hooks, specify reactive dependencies correctly.

4. Basic Syntax of a Custom Hook

import { useState } from 'react';

function useCustomHook() {
  const [value, setValue] = useState('');

  function updateValue(newValue) {
    setValue(newValue);
  }

  return {
    value,
    updateValue
  };
}

export default useCustomHook;

Explanation

  1. useCustomHook is the name of the Custom Hook.
  2. useState creates state inside the Hook.
  3. updateValue updates the state value.
  4. The Hook returns an object containing the current value and update function.
  5. A component can call the Custom Hook and use the returned data and functions.

5. Creating Your First Custom Hook: useCounter

In this example, we will create a reusable counter Hook that manages a number and provides functions to increase, decrease, and reset it.

Step 1: Create the Custom Hook

Create a file named useCounter.js.

import { useState } from 'react';

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

  const increment = () => {
    setCount(previousCount => previousCount + 1);
  };

  const decrement = () => {
    setCount(previousCount => previousCount - 1);
  };

  const reset = () => {
    setCount(initialValue);
  };

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

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>Counter: {count}</h2>
      <button onClick={increment}>Increase</button>
      <button onClick={decrement}>Decrease</button>
      <button onClick={reset}>Reset</button>
    </div>
  );
}

export default Counter;

How It Works

  1. The component calls useCounter(0) to initialize the counter.
  2. The Hook creates state using useState.
  3. The Hook returns the count and three functions.
  4. Clicking Increase increments the count.
  5. Clicking Decrease decrements the count.
  6. Clicking Reset returns the count to the initial value.

Important: Every call to useCounter has its own independent state. Custom Hooks share logic, not automatically a single shared state value.

6. Reusing a Custom Hook in Multiple Components

Custom Hooks become especially useful when multiple components need the same behavior but have different user interfaces.

import { useCounter } from './useCounter';

function CounterDisplay() {
  const { count } = useCounter(5);

  return <h2>Current Count: {count}</h2>;
}

function CounterControls() {
  const { count, increment } = useCounter(10);

  return (
    <div>
      <p>Control Count: {count}</p>
      <button onClick={increment}>Increase</button>
    </div>
  );
}

export { CounterDisplay, CounterControls };

In this example, the two components have separate counter states. Updating the counter in CounterControls does not automatically update CounterDisplay.

If multiple components must display and update the same state, lift the state into a common parent and pass it through props, or use a shared state solution such as Context or an appropriate state-management library.

7. Custom Hook for Form Handling: useFormInput

Forms often contain repeated logic for storing input values and handling changes. A Custom Hook can simplify this logic.

Step 1: Create useFormInput.js

import { useState } from 'react';

export function useFormInput(initialValue = '') {
  const [value, setValue] = useState(initialValue);

  function handleChange(event) {
    setValue(event.target.value);
  }

  return {
    value,
    onChange: handleChange
  };
}

Step 2: Use the Hook in a Form

import { useFormInput } from './useFormInput';

function RegistrationForm() {
  const firstName = useFormInput('');
  const email = useFormInput('');

  function handleSubmit(event) {
    event.preventDefault();

    console.log({
      firstName: firstName.value,
      email: email.value
    });
  }

  return (
    <form onSubmit={handleSubmit}>
      <label>
        First Name:
        <input
          value={firstName.value}
          onChange={firstName.onChange}
          required
        />
      </label>

      <label>
        Email:
        <input
          type="email"
          value={email.value}
          onChange={email.onChange}
          required
        />
      </label>

      <button type="submit">Register</button>
    </form>
  );
}

export default RegistrationForm;

Advantages of This Example

  • Input state management is separated from the form's presentation.
  • The same Hook can manage multiple fields.
  • Components become easier to read.
  • Each call maintains its own input state.

8. Custom Hook for Online Status: useOnlineStatus

A web application may need to display whether the user is connected to the internet. The browser provides online and offline events that can be handled through a Custom Hook.

Step 1: Create useOnlineStatus.js

import { useEffect, useState } from 'react';

export function useOnlineStatus() {
  const [isOnline, setIsOnline] = useState(
    typeof navigator === 'undefined' ? true : 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;
}

Step 2: Use the Hook in a Component

import { useOnlineStatus } from './useOnlineStatus';

function NetworkStatus() {
  const isOnline = useOnlineStatus();

  return (
    <div>
      <h2>Network Status</h2>
      <p>{isOnline ? 'You are online' : 'You are offline'}</p>
    </div>
  );
}

export default NetworkStatus;

Explanation: The Hook tracks the browser's online and offline events, updates its state when an event occurs, and removes the event listeners when the component using it is removed.

Note: The browser's online status does not guarantee that a particular website or server is reachable. For critical network operations, handle request failures as well.

9. Custom Hook for Fetching API Data: useFetch

Many React applications retrieve information from APIs. A Custom Hook can encapsulate loading state, response data, and error handling so multiple components can reuse that logic.

Step 1: Create useFetch.js

import { useEffect, useState } from 'react';

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

  useEffect(() => {
    if (!url) {
      setData(null);
      setError(null);
      setLoading(false);
      return;
    }

    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.message || 'Something went wrong');
        }
      } finally {
        if (!controller.signal.aborted) {
          setLoading(false);
        }
      }
    }

    fetchData();

    return () => {
      controller.abort();
    };
  }, [url]);

  return { data, loading, error };
}

Step 2: Use the Hook

import { useFetch } from './useFetch';

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

  if (loading) {
    return <p>Loading users...</p>;
  }

  if (error) {
    return <p>Error: {error}</p>;
  }

  return (
    <div>
      <h2>Users List</h2>
      <ul>
        {users?.map(user => (
          <li key={user.id}>{user.name}</li>
        ))}
      </ul>
    </div>
  );
}

export default Users;

How useFetch Works

  1. The component passes an API URL to the Hook.
  2. The Hook sets loading to true and starts the request.
  3. If the request succeeds, the returned JSON is stored in data.
  4. If the request fails, an error message is stored.
  5. The component displays loading, error, or data based on the returned state.
  6. The request is aborted during cleanup when the URL changes or the component using the Hook is removed.

Important: This is a learning example. Production data-fetching requirements may benefit from a dedicated library that handles caching, retries, request deduplication, and synchronization. Also, this Hook stores the most recent successful data; if a new request fails, previous data may remain in state.

10. Custom Hook for Toggle Functionality: useToggle

A toggle is used to switch a value between true and false. It can be useful for dark mode, menus, password visibility, accordions, and modal dialogs.

Custom Hook Code

import { useState } from 'react';

export function useToggle(initialValue = false) {
  const [value, setValue] = useState(initialValue);

  const toggle = () => {
    setValue(previousValue => !previousValue);
  };

  const setOn = () => setValue(true);
  const setOff = () => setValue(false);

  return {
    value,
    toggle,
    setOn,
    setOff
  };
}

Using useToggle

import { useToggle } from './useToggle';

function ToggleExample() {
  const {
    value: isVisible,
    toggle,
    setOff
  } = useToggle(false);

  return (
    <div>
      <button onClick={toggle}>
        {isVisible ? 'Hide Message' : 'Show Message'}
      </button>

      {isVisible && (
        <p>This message is visible.</p>
      )}

      <button onClick={setOff}>Close Message</button>
    </div>
  );
}

export default ToggleExample;

11. Custom Hooks and State Management

Custom Hooks can use state, but each invocation has independent Hook state. They do not automatically create a shared global state.

Requirement Recommended Approach
Reuse counter logic in multiple components Create a useCounter Custom Hook.
Share one counter value between sibling components Lift the state into a common parent or use Context where appropriate.
Share user authentication information across a component tree Consider Context or an established authentication/state-management solution.
Reuse form field behavior Create a form-related Custom Hook.
Reuse API loading and error logic Create a Custom Hook or use a data-fetching library.

12. Custom Hooks vs Regular JavaScript Functions

Feature Custom Hook Regular Function
Naming Starts with use, followed by a capital letter. Can have any valid JavaScript function name.
Can call React Hooks? Yes, at the top level. No, not as an ordinary function.
Purpose Reuse React stateful or Hook-based logic. Perform general calculations or operations.
Example useCounter() formatPrice()
Can be called conditionally? No, follow the Rules of Hooks. Yes, if normal JavaScript control flow allows it.

A function does not need to be a Custom Hook simply because it is reusable. If it does not use React Hooks and only performs a normal calculation, use a regular function.

13. Custom Hooks vs React Components

Feature Custom Hook React Component
Naming Starts with lowercase use. Usually starts with a capital letter.
Return value Can return values, objects, arrays, or functions. Returns React elements or other supported render output.
Purpose Encapsulates reusable logic. Describes the user interface.
Usage Called inside components or other Custom Hooks. Rendered through JSX or another supported React rendering mechanism.
Example const count = useCounter(); <Counter />

14. Best Practices for Custom Hooks

  • Choose descriptive names: Prefer names such as useOnlineStatus, useFormInput, and useFetch.
  • Keep each Hook focused: Avoid combining unrelated responsibilities in a single Hook.
  • Return only what callers need: A simple and clear API makes a Hook easier to reuse.
  • Follow the Rules of Hooks: Call Hooks only at the top level of a component or Custom Hook.
  • Keep rendering logic pure: Avoid changing external state during rendering.
  • Handle cleanup: Remove event listeners, clear timers, and abort requests when appropriate.
  • Manage dependencies carefully: Include reactive values used in Effects and memoized functions.
  • Avoid unnecessary abstractions: Do not create a Custom Hook for every small repeated expression if it makes the code more complicated.
  • Test behavior: Verify initial values, state changes, error cases, and cleanup behavior.
  • Document the API: Explain the parameters and return values for Hooks intended for reuse across a team.

15. Common Mistakes in Custom Hooks

Mistake 1: Using a Name That Does Not Start With use

// Avoid this name for a function that calls Hooks
function counterLogic() {
  const [count, setCount] = useState(0);
  return count;
}

Correction: Use a name such as useCounter. This makes Hook usage clear and helps React lint rules identify correct usage.

Mistake 2: Calling a Custom Hook Inside a Condition

// Incorrect
if (enabled) {
  const count = useCounter();
}

Correction: Call the Hook at the top level and use the enabled value to control behavior within the Hook or component.

Mistake 3: Assuming Multiple Hook Calls Share State

Calling useCounter() in two components creates separate counter state. To share the same state, use a common state owner or a shared state solution.

Mistake 4: Forgetting Effect Cleanup

Event listeners, subscriptions, and timers may continue running after they are no longer needed if cleanup is omitted. Return a cleanup function from useEffect when required.

Mistake 5: Missing Effect Dependencies

When a Custom Hook contains useEffect, missing dependencies can cause stale values or outdated behavior. Include the reactive values used by the Effect and follow the React Hooks lint rules.

Mistake 6: Creating a Custom Hook for Every Small Function

Not every helper function needs to be a Hook. If a function only transforms data and does not use React Hooks, a regular JavaScript function is usually more appropriate.

16. Practical Project: Reusable Search Hook

In this mini-project, we will create a Custom Hook that manages a search query and filters a list of items. This example demonstrates reusable state logic and filtering.

Step 1: Create useSearch.js

import { useMemo, useState } from 'react';

export function useSearch(items) {
  const [query, setQuery] = useState('');

  const filteredItems = useMemo(() => {
    const normalizedQuery = query.trim().toLowerCase();

    return items.filter(item =>
      item.toLowerCase().includes(normalizedQuery)
    );
  }, [items, query]);

  return {
    query,
    setQuery,
    filteredItems
  };
}

Step 2: Create the Search Component

import { useSearch } from './useSearch';

const fruits = [
  'Apple',
  'Banana',
  'Orange',
  'Mango',
  'Grapes',
  'Pineapple'
];

function FruitSearch() {
  const {
    query,
    setQuery,
    filteredItems
  } = useSearch(fruits);

  return (
    <div>
      <h2>Fruit Search</h2>

      <input
        type="text"
        value={query}
        onChange={event => setQuery(event.target.value)}
        placeholder="Search fruits..."
      />

      <ul>
        {filteredItems.map(fruit => (
          <li key={fruit}>{fruit}</li>
        ))}
      </ul>

      {filteredItems.length === 0 && (
        <p>No fruits found.</p>
      )}
    </div>
  );
}

export default FruitSearch;

Project Explanation

  1. The useSearch Hook receives an array of items.
  2. The Hook stores the search query using useState.
  3. useMemo calculates the filtered items when the items array or query changes.
  4. The Hook returns the query, the state setter, and the filtered results.
  5. The component displays the search input and matching fruit names.
  6. The same Hook can be reused for other string-based lists, provided the data and comparison logic are suitable.

Note: useMemo is used here as an optional performance optimization. For a very small list, the filtering calculation may be simple enough to perform without it.

17. Frequently Asked Interview Questions

Q1. What is a Custom Hook in React?

A Custom Hook is a reusable JavaScript function that can use React Hooks to encapsulate logic shared between components.

Q2. Why do we use Custom Hooks?

They help reduce duplicated logic, improve code organization, and make functionality easier to reuse and maintain.

Q3. What naming convention is used for Custom Hooks?

The name must begin with use followed by a capital letter, such as useCounter or useOnlineStatus.

Q4. Can a Custom Hook call another Custom Hook?

Yes. Custom Hooks can call built-in Hooks and other Custom Hooks, provided they follow the Rules of Hooks.

Q5. Do two components using the same Custom Hook share state?

No. Each call has independent state. To share state, lift it to a common parent or use an appropriate shared-state mechanism.

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

A component returns UI, while a Custom Hook returns reusable logic results such as state values, objects, or functions.

Q7. Can we use useEffect inside a Custom Hook?

Yes. A Custom Hook can use useEffect to synchronize with external systems, such as browser events, subscriptions, and network requests.

Q8. Can we call a Custom Hook conditionally?

No. Hooks must be called at the top level of a component or Custom Hook, not inside conditions or loops.

Q9. Can a Custom Hook return an object?

Yes. It can return an object containing state values and functions, an array, a single value, or another suitable result.

Q10. Should all reusable functions be Custom Hooks?

No. A function that does not use React Hooks and simply performs a calculation or transformation should usually remain a regular JavaScript function.

Q11. What is a practical example of a Custom Hook?

Examples include useCounter, useFormInput, useOnlineStatus, useToggle, and useFetch.

Q12. How do you handle cleanup in a Custom Hook?

If the Hook uses an Effect to set up a subscription, event listener, or timer, the Effect should return a cleanup function when required.

18. Practice Exercises

  1. Create a useCounter Hook with increment, decrement, and reset functions.
  2. Create a useToggle Hook to show and hide a password.
  3. Create a useFormInput Hook for a registration form with name and email fields.
  4. Create a useOnlineStatus Hook that displays the current browser online status.
  5. Create a useFetch Hook that manages loading, data, and error states.
  6. Create a useSearch Hook to filter a list of products.
  7. Use one Custom Hook in two components and observe that their state is independent.
  8. Refactor repeated stateful logic from two components into a single Custom Hook.

19. Quick Revision Checklist

  • ☑ Custom Hooks allow reusable Hook-based logic.
  • ☑ Custom Hook names start with use.
  • ☑ A Custom Hook can call built-in Hooks and other Custom Hooks.
  • ☑ Hooks must be called at the top level of React components or Custom Hooks.
  • ☑ Custom Hooks share logic, not automatically the same state.
  • ☑ State can be shared by lifting it into a common parent or using an appropriate shared-state solution.
  • ☑ Effects may require cleanup for subscriptions, listeners, and timers.
  • ☑ Use clear names and keep each Hook focused on a specific responsibility.
  • ☑ Ordinary helper functions do not need to be Custom Hooks.

20. Official React Documentation

21. React JS Training Resources

To learn more about React JS, functional components, built-in Hooks, Custom Hooks, state management, and reusable application development, explore these training resources:

22. Conclusion

Custom Hooks help React developers create reusable and organized logic for common application requirements. By combining built-in Hooks such as useState and useEffect, developers can build functions like useCounter, useFormInput, useOnlineStatus, and useFetch. Using Custom Hooks appropriately reduces duplication, improves readability, and makes React applications easier to maintain. Always follow the Rules of Hooks and remember that Custom Hooks reuse logic rather than automatically sharing state.

Previous Next
whatsapp