🎣 React Hooks – In-Depth
Estimated reading: 4 minutes 38 views

🎣 React Custom Hooks – Build Reusable Logic for Functional Components (2025 Guide)


🧲 Introduction – Why Use Custom Hooks?

In React.js, hooks like useState, useEffect, and useContext provide powerful features within functional components. But as apps grow, you may notice repeated patterns across components β€” like fetching data, form handling, or toggling state.

That’s where Custom Hooks come in.

Custom Hooks let you extract and reuse logic across multiple components, keeping your code clean, modular, and maintainable.

🎯 In this guide, you’ll learn:

  • What custom hooks are and how to create them
  • When and why to use them
  • Real-world examples (toggle, fetch, form)
  • Best practices and naming conventions

🧩 What Are Custom Hooks?

A custom hook is simply a JavaScript function that starts with use and uses built-in hooks inside it.

βœ… Syntax:

function useCustomHook() {
  // useState, useEffect, etc.
  return something;
}

πŸ“˜ It allows you to reuse hook logic across components without copying and pasting.


βš™οΈ 1. Custom Toggle Hook Example

βœ… useToggle.js

import { useState, useCallback } from 'react';

export function useToggle(initial = false) {
  const [value, setValue] = useState(initial);
  const toggle = useCallback(() => setValue(prev => !prev), []);
  return [value, toggle];
}

βœ… Usage:

const [isOpen, toggleOpen] = useToggle();

βœ… Perfect for dropdowns, modals, tooltips, etc.


🌐 2. Custom Fetch Hook (API Request)

βœ… useFetch.js

import { useState, useEffect } from 'react';

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

  useEffect(() => {
    setLoading(true);
    fetch(url)
      .then(res => res.json())
      .then(setData)
      .catch(setError)
      .finally(() => setLoading(false));
  }, [url]);

  return { data, loading, error };
}

βœ… Usage:

const { data, loading, error } = useFetch('/api/users');

βœ… Abstracts API logic into one reusable hook


🧾 3. Custom Form Hook

βœ… useForm.js

import { useState } from 'react';

export function useForm(initialValues = {}) {
  const [values, setValues] = useState(initialValues);

  const handleChange = e => {
    const { name, value } = e.target;
    setValues(prev => ({ ...prev, [name]: value }));
  };

  const reset = () => setValues(initialValues);

  return { values, handleChange, reset };
}

βœ… Usage:

const { values, handleChange, reset } = useForm({ name: '', email: '' });

βœ… Simplifies controlled form inputs and state resets


🧠 4. Why Custom Hooks Are Powerful

BenefitDescription
♻️ ReusabilityShare stateful logic across components
🧼 Clean CodeEliminate duplication and improve readability
πŸ”§ CompositionHooks can call other hooks β€” logic is modular
πŸ“¦ AbstractionEncapsulate complex behavior into readable units
πŸ”’ IsolationKeeps concerns separate and testable

πŸ” 5. Rules for Custom Hooks

βœ… Must start with use
βœ… Must follow Hooks rules:

  • Only call hooks at the top level
  • Only call hooks inside React functions (components or custom hooks)

βœ… Can use any built-in hooks (useState, useEffect, etc.)
βœ… Can return values, functions, or objects


πŸ“˜ Best Practices

βœ… Name your custom hook descriptively: useToggle, useForm, useFetch
βœ… Use useCallback, useMemo inside custom hooks when needed
βœ… Return only what’s needed: values, actions, booleans
βœ… Keep each hook single-purpose and focused


πŸ“Œ Summary – Recap & Next Steps

Custom Hooks allow you to write cleaner, more modular code by extracting repeated logic into reusable functions. They promote consistency, simplify components, and enhance maintainability in any React application.

πŸ” Key Takeaways:

  • Custom hooks are functions that use other React hooks
  • Reuse logic for toggling, fetching, forms, and more
  • Follow hook naming conventions (useX) and rules
  • Combine multiple hooks to build advanced custom hooks

βš™οΈ Real-World Relevance:
Custom Hooks are widely used in production apps like Notion, Stripe, Shopify, and internal tools where component logic needs to be reused across modules.


❓ FAQ Section

❓ What makes a hook “custom”?
βœ… Any function that starts with use and calls built-in React hooks is considered a custom hook.


❓ Can I use state and effects inside a custom hook?
βœ… Yes! That’s exactly what they’re for:

function useMyHook() {
  const [count, setCount] = useState(0);
  useEffect(() => { ... }, []);
}

❓ Can custom hooks return functions?
βœ… Absolutely. You can return anything: values, objects, handlers, etc.


❓ Can I share custom hooks between projects?
βœ… Yes! You can extract them into a shared hooks library or even publish them as NPM packages.


❓ Are custom hooks the same as HOCs or Render Props?
❌ No. But they replace most use cases for HOCs and Render Props in functional components.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

πŸ” React Custom Hooks – Reusable Logic

Or Copy Link

CONTENTS
Scroll to Top