Introduction to Custom Hooks

🪝 What Are Custom Hooks?

A Custom Hook is a JavaScript function that allows you to extract and reuse stateful logic across multiple React components. Like built-in Hooks, a custom Hook can call other Hooks such as useState, useEffect, useContext, and more.

Important

A custom Hook is simply a function whose name starts with use. This naming convention tells React and other developers that the function follows the Rules of Hooks.

🎯 Why Use Custom Hooks?

As React applications grow, different components often contain similar state management and side-effect logic. Copying the same code into multiple components makes maintenance difficult. Custom Hooks allow this shared logic to be extracted into a reusable function while keeping each component clean and focused.

  • Reuse stateful logic across multiple components.
  • Reduce duplicate code.
  • Keep components smaller and easier to understand.
  • Improve code organization and maintainability.

📦 What Makes a Hook "Custom"?

CharacteristicDescription
FunctionA custom Hook is an ordinary JavaScript function.
NameIts name must begin with use.
Uses HooksIt can call built-in Hooks or other custom Hooks.
ReusableIts logic can be shared across multiple components.

🔄 How Custom Hooks Work

Component Needs Shared Logic
Extract the Logic into a Custom Hook
Custom Hook Uses Built-in Hooks
Multiple Components Call the Custom Hook
Each Component Gets Its Own Independent State

💻 Example 1: A Simple Custom Hook

Creating a Custom Hook

import { useState } from "react";

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

  function increment() {
    setCount(c => c + 1);
  }

  return {
    count,
    increment
  };
}

This custom Hook encapsulates counter logic so it can be reused in any component.

💻 Example 2: Using the Custom Hook

Using useCounter

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

  return (
    <>
      <h2>{count}</h2>

      <button onClick={increment}>
        Increment
      </button>
    </>
  );
}

Every component that calls useCounter() receives its own independent state while reusing the same logic.

📊 Component Logic vs Custom Hook

Without Custom HooksWith Custom Hooks
Logic is duplicated across components.Shared logic exists in one reusable function.
Larger, harder-to-maintain components.Smaller, focused components.
Changes must be repeated everywhere.Update the custom Hook once.
Lower code reusability.Higher code reusability.

📅 Custom Hook Lifecycle

🎯 Common Use Cases

Reuse form state, validation, and input handling across multiple forms.

Encapsulate data fetching and loading logic in a reusable Hook.

Share login, logout, and user session logic throughout an application.

Wrap browser APIs such as network status, window size, or geolocation in reusable Hooks.

⚠️ Rules for Custom Hooks

  • Always start the Hook name with use.
  • Call Hooks only at the top level of the custom Hook.
  • Do not call Hooks inside loops, conditions, or nested functions.
  • Use custom Hooks only inside React components or other custom Hooks.

Warning

A custom Hook shares logic, not state. Every component that uses a custom Hook gets its own independent state.

✅ Best Practices

  • Extract only reusable logic into custom Hooks.
  • Keep each custom Hook focused on a single responsibility.
  • Return only the values and functions that consumers need.
  • Compose small custom Hooks together to build more powerful abstractions.
  • Use clear, descriptive names such as useCounter, useFetch, or useOnlineStatus.

📚 Official Resource

Learn more about custom Hooks in the official React documentation at Reusing Logic with Custom Hooks.

Summary

Custom Hooks allow you to extract and reuse stateful logic across React components. They help eliminate duplicate code, improve maintainability, and keep components focused on rendering rather than implementation details. By following the Rules of Hooks and designing Hooks with a single responsibility, you can build clean, reusable, and scalable React applications.