KoderSolution Logo
HomeArticlesTutorialsForumAI LabRun Code
KoderSolution Logo

The world’s most advanced technical ecosystem for modern software engineers. Learn, build, and grow with next-generation developer tools and resources.

Engineering Newsletter

Join 100,000+ engineers receiving curated high-signal content weekly.

Platforms

  • Technical Articles
  • Interactive Tutorials
  • AI Coding Lab
  • Developer Forum
  • Developer Tools

Pages

  • About Us
  • Contact Us
  • Privacy Policy
  • Terms of Service
  • Refund Policy
  • Disclaimer
  • Advertisement

Popular Topics

  • PHP
  • Laravel
  • Python
  • React.Js
  • MySQL
© 2026 KoderSolutionAll Rights Reserved
Developed Bymaksudur.dev
⚛️

React

Topic Hub & Articles

React Intro

10 min

Recap Quiz

5 Questions

React Getting Started

10 min

React ES6

10 min

React Render HTML

10 min

Recap Quiz

5 Questions

React JSX

10 min

React Components

10 min

React Class Components

10 min

Recap Quiz

5 Questions

React Props

10 min

React Events

10 min

React Conditionals

10 min

Recap Quiz

5 Questions

React Lists

10 min

React Forms

10 min

React Router

10 min

Recap Quiz

5 Questions

React Memo

10 min

React CSS Styling

10 min

React Sass Styling

10 min

Recap Quiz

5 Questions

React Fragments

10 min

React Portals

10 min

React Profiler

10 min

Recap Quiz

5 Questions

React Strict Mode

10 min

React Higher Order Components

10 min

React Context API

10 min

React Error Boundaries

10 min

What is a Hook

10 min

Recap Quiz

5 Questions

useState

10 min

useEffect

10 min

useContext

10 min

Recap Quiz

5 Questions

useRef

10 min

useReducer

10 min

useCallback

10 min

Recap Quiz

5 Questions

useMemo

10 min

Custom Hooks

10 min

useLayoutEffect

10 min

Recap Quiz

5 Questions

useImperativeHandle

10 min

useDebugValue

10 min

useDeferredValue

10 min

Recap Quiz

5 Questions

useTransition

10 min

useId

10 min

Progress
0%

0 / 38 Lessons

ReactReact Hooks
Lesson

Custom Hooks

10 min reading
Free Course

Custom Hooks: Encapsulated & Reusable Reactive Logic

A Custom Hook is a JavaScript function whose name starts with "use" and that can call other React hooks. Custom hooks enable developers to extract component state logic into reusable, testable functions shared across multiple components.

Custom Hook Architecture

flowchart TD
    CompA["Component A"] --> CustomHook["useFetch('/api/data')"]
    CompB["Component B"] --> CustomHook
    CustomHook --> ReactHooks["Encapsulated useState + useEffect"]

Practical Example 1: useFetch Custom Hook

import { useState, useEffect } from 'react';

// Reusable Custom Hook for HTTP Data Fetching
export function useFetch(url) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    let isMounted = true;
    setLoading(true);

    fetch(url)
      .then((res) => {
        if (!res.ok) throw new Error(`HTTP Error status: ${res.status}`);
        return res.json();
      })
      .then((json) => {
        if (isMounted) setData(json);
      })
      .catch((err) => {
        if (isMounted) setError(err.message);
      })
      .finally(() => {
        if (isMounted) setLoading(false);
      });

    return () => {
      isMounted = false;
    };
  }, [url]);

  return { data, loading, error };
}

Practical Example 2: useLocalStorage Custom Hook

import { useState, useEffect } from 'react';

export function useLocalStorage(key, initialValue) {
  const [storedValue, setStoredValue] = useState(() => {
    try {
      const item = window.localStorage.getItem(key);
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      return initialValue;
    }
  });

  useEffect(() => {
    try {
      window.localStorage.setItem(key, JSON.stringify(storedValue));
    } catch (error) {
      console.error('LocalStorage write error:', error);
    }
  }, [key, storedValue]);

  return [storedValue, setStoredValue];
}

Consuming Custom Hooks in Components

import React from 'react';
import { useFetch } from './useFetch';
import { useLocalStorage } from './useLocalStorage';

export default function UserDashboard() {
  const { data: users, loading, error } = useFetch('https://jsonplaceholder.typicode.com/users');
  const [savedTheme, setSavedTheme] = useLocalStorage('preferred_theme', 'dark');

  if (loading) return <p>Loading remote users...</p>;
  if (error) return <p>Error loading data: {error}</p>;

  return (
    <div>
      <h2>User Count: {users?.length}</h2>
      <button onClick={() => setSavedTheme(savedTheme === 'dark' ? 'light' : 'dark')}>
        Theme: {savedTheme}
      </button>
    </div>
  );
}

Best Practices & Gotchas

  • Hook Names Must Start With "use": React lint rules rely on the "use" prefix to automatically enforce the Rules of Hooks on custom functions.
  • State Inside Custom Hooks Is Isolated: Calling useFetch inside two different components does NOT share state between them; each component call creates an isolated state instance.

Self-Check Challenge

Create a custom hook useWindowSize() that returns { width, height } and updates on browser window resize events.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Recommended Courses & Books

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum