Monday, June 1, 2026

React Custom Hooks

React custom hooks are reusable JavaScript functions that encapsulate stateful logic, allowing you to share functionality across multiple components without duplicating code. They act as clean abstractions that combine React's built-in hooks (like useState and useEffect) into a single, cohesive engine.

Core Rules for Custom Hooks

  • Name must start with "use": The prefix use (e.g., useFetch, useAuth) is mandatory so React's linter can identify it and enforce hook rules.
  • Isolated state: Two components using the exact same custom hook do not share state. Each execution initializes an independent sandbox of state and side-effects.
  • Top-level execution: They must be executed only at the top level of your components or other custom hooks, never inside loops, conditions, or nested functions.

Step-by-Step Practical Example

Consider an application requiring network status verification. Instead of hardcoding window event listeners in every individual component, you can isolate the logic inside a single hook.

1. Define the Custom Hook

Create a file named useOnlineStatus.js to manage the underlying state and side effects:

import { useState, useEffect } from 'react';

export function useOnlineStatus() {
  const [isOnline, setIsOnline] = useState(navigator.onLine);

  useEffect(() => {
    const handleOnline = () => setIsOnline(true);
    const handleOffline = () => setIsOnline(false);

    window.addEventListener('online', handleOnline);
    window.addEventListener('offline', handleOffline);

    // Clean up event listeners on unmount to prevent memory leaks
    return () => {
      window.removeEventListener('online', handleOnline);
      window.removeEventListener('offline', handleOffline);
    };
  }, []);

  return isOnline;
}

Use code with caution.

2. Consuming the Hook in Components

You can now pull this isolated logic directly into any functional component:

import { useOnlineStatus } from './useOnlineStatus';

export default function StatusBar() {
  const isOnline = useOnlineStatus();

  return (
    <h1>
      {isOnline ? '✅ Connected' : '❌ Disconnected'}
    </h1>
  );
}

Use code with caution.

Common Use Cases

  • Data Fetching: Consolidating fetch workflows, loading states, and error parsing into a structured useFetch module.
  • Form Handling: Creating a useForm utility to track user inputs, handle reset triggers, and run validations dynamically.
  • Event Listeners: Tracking mouse positions, window resizing, or keyboard strokes cleanly with automated event cleanup.
  • Storage Interactivity: Syncing component states directly with localStorage or sessionStorage.
Learning Resource

Explore the official guide on Reusing Logic with Custom Hooks from the React documentation to dive deeper into custom design patterns.

No comments:

Post a Comment

React Custom Hooks

React custom hooks are reusable JavaScript functions that encapsulate stateful logic, allowing you to share functionality a...