OnlineCBT Logo OnlineCBT
React Tutorial
REACT · LESSON 11

Custom Hooks Creation

By Ratan Updated: 16 Oct 2026

Encapsulate reusable stateful logic into custom reusable React Hooks (useFetch, useForm, etc.).

Level: Beginner to Advanced
Duration: ~60 Mins Deep-Dive

1. Why Create Custom Hooks?

In React, components reuse UI structures. But when you need to reuse stateful logic (such as window resizing, local storage synchronization, or API fetching) across multiple unrelated components, you extract that logic into a Custom Hook.

2. Rules for Custom Hooks

  • A custom hook is a JavaScript function whose name must begin with use (e.g. useLocalStorage, useFetch, useOnlineStatus).
  • Custom hooks can call other React hooks (like useState, useEffect).

3. Creating a useLocalStorage Custom Hook

import { useState, useEffect } from 'react';

export function useLocalStorage(key, initialValue) {
  // Read existing value from localStorage on first render
  const [storedValue, setStoredValue] = useState(() => {
    try {
      const item = localStorage.getItem(key);
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      console.error("Error reading localStorage key:", key, error);
      return initialValue;
    }
  });

  // Automatically write to localStorage whenever storedValue changes
  useEffect(() => {
    try {
      localStorage.setItem(key, JSON.stringify(storedValue));
    } catch (error) {
      console.error("Error writing to localStorage:", error);
    }
  }, [key, storedValue]);

  return [storedValue, setStoredValue];
}

4. Using Your Custom Hook in Components

import { useLocalStorage } from './useLocalStorage';

function ExamThemeSelector() {
  // Seamlessly stays in sync with browser localStorage!
  const [theme, setTheme] = useLocalStorage("cbt_theme", "light");

  return (
    
  );
}

📝 Live Lesson Practice

HTML/CSS JavaScript Python C++ C PHP
⌨️ Practice Inputs (लाइव इनपुट भरें) (खाली होने पर RED, भरने पर GREEN underline)
💻 Code Editor (Monaco VS Code Engine)
👀 Live Preview
पता संपर्क करें

+91 7877547686

ई-मेल

onlinecbtportal@gmail.com

हेल्पलाइन नंबर

+91 7877547686


डाउनलोड करने के लिए क्लिक करें
Get it on Google Play

ऐप डाउनलोड करने
के लिए Google Play पर
उपलब्ध है

WhatsApp Chat