Advanced Hooks
Dashboard
Topic 6/10
Home › React › Advanced Hooks

⚡ Advanced Hooks

useContext, useReducer, useMemo, useCallback, useRef, and custom hooks.

Summary of Advanced Hooks

Overview of performance and state management hooks.

Hook Purpose Best Use Case
useContext Access Context values directly Avoid prop drilling for Theme, Auth, User data.
useReducer Manage complex state logic Form wizards, multi-action complex states.
useMemo Memoize expensive calculations Filtering / sorting large data arrays.
useCallback Memoize function references Prevent unnecessary child re-renders.
useRef Mutable ref object DOM node access, storing previous state/timers.

Custom Hooks

Custom hooks extract reusable stateful logic into standalone JavaScript functions.

useFetch.js JavaScript
import { useState, useEffect } from 'react';

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

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

  return { data, loading };
}