React Js

React JS Tutorial Learn React JS, the powerful JavaScript library for building dynamic and interactive user interfaces. This beginner-friendly tutorial covers core concepts like components, state, props, and hooks, with hands-on projects to create responsive web apps. Perfect for aspiring developers looking to master modern front-end development.

React Custom Hooks

25 April 2025 | Category:

What Are Custom Hooks?

In React, Custom Hooks are functions that start with the word use and allow you to reuse stateful logic across components.

Think of them like your own versions of useState, useEffect, or useRef, created to solve repeated patterns in your app.


✅ Why Use Custom Hooks?

Here’s why custom hooks are powerful:

  • ♻️ Reusability: Avoid repeating the same logic in multiple components.
  • 🧼 Clean Code: Keep components focused on rendering UI, not logic.
  • 🔧 Organized Structure: Isolate side effects, state, or reusable behaviors.
  • 🤝 Composable: Combine multiple hooks to create complex behavior.

🔧 How to Create a Custom Hook

✅ Step-by-Step:

  1. Create a function starting with the word use
  2. Use built-in hooks inside it like useState, useEffect, etc.
  3. Return whatever values or functions you want to use in components

📌 Example 1: useWindowWidth – Track window width

import { useState, useEffect } from 'react';

function useWindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);

  useEffect(() => {
    const handleResize = () => setWidth(window.innerWidth);
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  return width;
}

👇 Using it in a component:

function App() {
  const width = useWindowWidth();

  return <h2>Window width: {width}px</h2>;
}

📌 Example 2: useFetch – Custom data fetching hook

import { useState, useEffect } from 'react';

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

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

  return { data, loading };
}

👇 Using useFetch in a component:

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

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

  return (
    <ul>
      {data.map(user => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}

🎯 Best Practices for Custom Hooks

Always start hook names with use
Use other hooks inside (like useState, useEffect)
Isolate reusable logic only, not UI
Return what’s needed (state, functions, etc.)
Keep them pure and predictable


📋 Summary Table

FeatureDescription
Custom HookA reusable function with logic using React Hooks
Starts withuse
Uses built-in hooksLike useState, useEffect, etc.
ImprovesCode reusability and readability
ReturnsData, state, or functions

🔥 Real-World Custom Hook Ideas

  • useLocalStorage – Get/set localStorage data
  • useToggle – Toggle boolean state (e.g., modal open/close)
  • useForm – Handle input values and validation
  • usePrevious – Track the previous value of a variable
  • useDebounce – Delay updates to prevent rapid state changes