Skip to main content
FREE Mock interview & resume review with Sumit. Free right now, no payment needed.Book a slot

Creating Custom React Hooks

Learn how to extract component logic into reusable custom hooks. Build reusable custom hooks to share logic across components and improve code organization.

jiocoder TeamUpdated Jun 6, 20266 min readReact
Creating Custom React Hooks

What are Custom Hooks?#

Custom hooks are JavaScript functions that start with "use" and can call other React hooks. They allow you to extract component logic into reusable functions. Custom hooks enable you to share stateful logic between components without duplicating code or using higher-order components.

The beauty of custom hooks is that they follow the same rules as regular hooks - they can call other hooks, and React will track their state correctly. This makes them perfect for encapsulating complex logic that you want to reuse across multiple components.

Installation#

Custom hooks are just regular JavaScript functions, so no installation is needed. They're part of React's hooks system (React 16.8+). To create a custom hook, simply create a function that starts with "use" and calls other hooks:

Code
// hooks/useCustomHook.js
import { useState, useEffect } from 'react';

export function useCustomHook(initialValue) {
  const [value, setValue] = useState(initialValue);
  // ... hook logic
  return value;
}

Rules of Custom Hooks#

  • Must start with "use" (React convention)
  • Can call other hooks
  • Should be pure functions (no side effects in the function body itself)
  • Can return any value (primitive, object, array, function, etc.)

Example: useFetch Hook#

One of the most common custom hooks is for data fetching:

Code
import { useState, useEffect } from 'react';

function useFetch(url, options = {}) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  
  useEffect(() => {
    let cancelled = false;
    
    async function fetchData() {
      try {
        setLoading(true);
        setError(null);
        
        const response = await fetch(url, options);
        
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const json = await response.json();
        
        if (!cancelled) {
          setData(json);
        }
      } catch (err) {
        if (!cancelled) {
          setError(err.message);
        }
      } finally {
        if (!cancelled) {
          setLoading(false);
        }
      }
    }
    
    fetchData();
    
    // Cleanup function to cancel request if component unmounts
    return () => {
      cancelled = true;
    };
  }, [url, JSON.stringify(options)]);
  
  return { data, loading, error };
}

// Usage in component
function UserProfile({ userId }) {
  const { data, loading, error } = useFetch(`/api/users/${userId}`);
  
  if (loading) return <div className="loading">Loading...</div>;
  if (error) return <div className="error">Error: {error}</div>;
  if (!data) return null;
  
  return (
    <div className="user-profile">
      <h2>{data.name}</h2>
      <p>{data.email}</p>
    </div>
  );
}

Example: useLocalStorage Hook#

Sync component state with localStorage:

Code
import { useState, useEffect } from 'react';

function useLocalStorage(key, initialValue) {
  // State to store our value
  const [storedValue, setStoredValue] = useState(() => {
    try {
      // Get from local storage by key
      const item = window.localStorage.getItem(key);
      // Parse stored json or if none return initialValue
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      // If error also return initialValue
      console.error(`Error reading localStorage key "${key}":`, error);
      return initialValue;
    }
  });
  
  // Return a wrapped version of useState's setter function that
  // persists the new value to localStorage.
  const setValue = (value) => {
    try {
      // Allow value to be a function so we have same API as useState
      const valueToStore = value instanceof Function ? value(storedValue) : value;
      // Save state
      setStoredValue(valueToStore);
      // Save to local storage
      window.localStorage.setItem(key, JSON.stringify(valueToStore));
    } catch (error) {
      console.error(`Error setting localStorage key "${key}":`, error);
    }
  };
  
  return [storedValue, setValue];
}

// Usage
function Settings() {
  const [theme, setTheme] = useLocalStorage('theme', 'light');
  const [language, setLanguage] = useLocalStorage('language', 'en');
  
  return (
    <div>
      <select value={theme} onChange={(e) => setTheme(e.target.value)}>
        <option value="light">Light</option>
        <option value="dark">Dark</option>
      </select>
    </div>
  );
}

Example: useDebounce Hook#

Debounce values to limit how often a function runs:

Code
import { useState, useEffect } from 'react';

function useDebounce(value, delay) {
  const [debouncedValue, setDebouncedValue] = useState(value);
  
  useEffect(() => {
    // Set debouncedValue to value after the specified delay
    const handler = setTimeout(() => {
      setDebouncedValue(value);
    }, delay);
    
    // Cancel the timeout if value changes (also on delay change or unmount)
    return () => {
      clearTimeout(handler);
    };
  }, [value, delay]);
  
  return debouncedValue;
}

// Usage: Search input with debounce
function SearchInput() {
  const [searchTerm, setSearchTerm] = useState('');
  const debouncedSearchTerm = useDebounce(searchTerm, 500);
  
  useEffect(() => {
    if (debouncedSearchTerm) {
      // Perform search API call
      performSearch(debouncedSearchTerm);
    }
  }, [debouncedSearchTerm]);
  
  return (
    <input
      type="text"
      value={searchTerm}
      onChange={(e) => setSearchTerm(e.target.value)}
      placeholder="Search..."
    />
  );
}

Example: useToggle Hook#

Simple toggle functionality:

Code
import { useState, useCallback } from 'react';

function useToggle(initialValue = false) {
  const [value, setValue] = useState(initialValue);
  
  const toggle = useCallback(() => {
    setValue(v => !v);
  }, []);
  
  const setTrue = useCallback(() => {
    setValue(true);
  }, []);
  
  const setFalse = useCallback(() => {
    setValue(false);
  }, []);
  
  return [value, { toggle, setTrue, setFalse, setValue }];
}

// Usage
function Modal() {
  const [isOpen, { toggle, setTrue, setFalse }] = useToggle(false);
  
  return (
    <div>
      <button onClick={toggle}>Toggle Modal</button>
      {isOpen && (
        <div className="modal">
          <button onClick={setFalse}>Close</button>
          Modal Content
        </div>
      )}
    </div>
  );
}

Example: useWindowSize Hook#

Track window dimensions:

Code
import { useState, useEffect } from 'react';

function useWindowSize() {
  const [windowSize, setWindowSize] = useState({
    width: typeof window !== 'undefined' ? window.innerWidth : 0,
    height: typeof window !== 'undefined' ? window.innerHeight : 0,
  });
  
  useEffect(() => {
    function handleResize() {
      setWindowSize({
        width: window.innerWidth,
        height: window.innerHeight,
      });
    }
    
    window.addEventListener('resize', handleResize);
    handleResize(); // Set initial size
    
    return () => window.removeEventListener('resize', handleResize);
  }, []);
  
  return windowSize;
}

// Usage
function ResponsiveComponent() {
  const { width, height } = useWindowSize();
  const isMobile = width < 768;
  
  return (
    <div className={isMobile ? 'mobile' : 'desktop'}>
      Window size: {width} x {height}
    </div>
  );
}

Example: usePrevious Hook#

Track the previous value of a prop or state:

Code
import { useRef, useEffect } from 'react';

function usePrevious(value) {
  const ref = useRef();
  
  useEffect(() => {
    ref.current = value;
  }, [value]);
  
  return ref.current;
}

// Usage
function Counter({ count }) {
  const prevCount = usePrevious(count);
  
  return (
    <div>
      <p>Current: {count}</p>
      <p>Previous: {prevCount}</p>
      {count > prevCount && <p>Increased!</p>}
    </div>
  );
}

Example: useClickOutside Hook#

Detect clicks outside an element:

Code
import { useEffect, useRef } from 'react';

function useClickOutside(callback) {
  const ref = useRef(null);
  
  useEffect(() => {
    function handleClickOutside(event) {
      if (ref.current && !ref.current.contains(event.target)) {
        callback();
      }
    }
    
    document.addEventListener('mousedown', handleClickOutside);
    document.addEventListener('touchstart', handleClickOutside);
    
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
      document.removeEventListener('touchstart', handleClickOutside);
    };
  }, [callback]);
  
  return ref;
}

// Usage
function Dropdown() {
  const [isOpen, setIsOpen] = useState(false);
  const dropdownRef = useClickOutside(() => setIsOpen(false));
  
  return (
    <div ref={dropdownRef}>
      <button onClick={() => setIsOpen(!isOpen)}>Toggle</button>
      {isOpen && (
        <div className="dropdown-menu">
          Menu items
        </div>
      )}
    </div>
  );
}

Best Practices#

  • Start hook names with "use" - This is a React convention that helps identify hooks
  • Extract reusable logic - Only create custom hooks for logic used in multiple components
  • Return values/objects consistently - Use consistent return patterns (array or object)
  • Document hook dependencies - Comment on what the hook depends on
  • Handle edge cases - Consider cleanup, cancellation, and error states
  • Keep hooks focused - One hook should do one thing well
  • Test hooks separately - Use @testing-library/react-hooks for testing
  • Share hooks in a hooks directory - Organize custom hooks in a dedicated folder

Organizing Custom Hooks#

Create a hooks directory structure:

Code
src/
  hooks/
    useFetch.js
    useLocalStorage.js
    useDebounce.js
    useToggle.js
    index.js  // Export all hooks
Code
// hooks/index.js
export { useFetch } from './useFetch';
export { useLocalStorage } from './useLocalStorage';
export { useDebounce } from './useDebounce';
export { useToggle } from './useToggle';

Testing Custom Hooks#

Test custom hooks using React Testing Library:

Code
import { renderHook, act } from '@testing-library/react-hooks';
import { useToggle } from './useToggle';

test('should toggle value', () => {
  const { result } = renderHook(() => useToggle(false));
  
  expect(result.current[0]).toBe(false);
  
  act(() => {
    result.current[1].toggle();
  });
  
  expect(result.current[0]).toBe(true);
});

Custom hooks are a powerful way to share logic between React components. They make your code more reusable, testable, and maintainable. By extracting common patterns into custom hooks, you can build a library of reusable functionality that makes your React applications cleaner and more efficient.

Article discussion

(0)

Join the discussion — login to comment and help other developers.

Login to comment