JavaScript and React course ยท Module 5: useEffect and Custom Hooks

Custom Hooks for Effects

5 min read ยท
In this lesson6

On our cosmic journey through React, repeatedly writing the same useEffect patterns in different components is like building identical navigation systems from scratch for every ship in the fleet. Custom Hooks allow you to extract repeatable effect logic into a single, reusable function - like creating a propulsion module that can be installed in any ship.

What are Custom Hooks?

A Custom Hook is a regular JavaScript function whose name starts with use and which can call other hooks (useState, useEffect, useRef, etc.). It's not any special React syntax - the only convention is the use prefix.

// Custom Hook - extracted logic
function useWindowSize() {
  const [size, setSize] = useState({
    width: window.innerWidth,
    height: window.innerHeight
  });

  useEffect(() => {
    const handleResize = () => {
      setSize({ width: window.innerWidth, height: window.innerHeight });
    };

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  return size;
}

// Usage in a component - clean and simple
function SpaceshipCockpit() {
  const { width, height } = useWindowSize();

  return (
    <p>
      Cockpit screen size: {width} x {height}
    </p>
  );
}

Notice that useWindowSize contains useState and useEffect with cleanup inside - all the logic is enclosed in a single hook, and the component gets a ready result.

useFetch - data fetching

One of the most common custom hooks is a data fetching hook. Instead of repeating the loading/error/data pattern in every component, we encapsulate it in useFetch:

function useFetch(url) {
  const [data, setData] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const controller = new AbortController();
    setIsLoading(true);
    setError(null);

    fetch(url, { signal: controller.signal })
      .then(response => {
        if (!response.ok) throw new Error('Network error');
        return response.json();
      })
      .then(data => {
        setData(data);
        setIsLoading(false);
      })
      .catch(err => {
        if (err.name !== 'AbortError') {
          setError(err.message);
          setIsLoading(false);
        }
      });

    // Cleanup - cancel request on unmount or URL change
    return () => controller.abort();
  }, [url]);

  return { data, isLoading, error };
}

Now any component that needs API data can use a single line:

function CrewList() {
  const { data: crew, isLoading, error } = useFetch('/api/crew');

  if (isLoading) return <p>Loading crew...</p>;
  if (error) return <p>Error: {error}</p>;

  return (
    <ul>
      {crew.map(member => (
        <li key={member.id}>{member.name}</li>
      ))}
    </ul>
  );
}

function MissionLog() {
  const { data: missions, isLoading } = useFetch('/api/missions');

  if (isLoading) return <p>Loading missions...</p>;

  return missions.map(m => <div key={m.id}>{m.name}</div>);
}

Two components, same data fetching pattern - zero code duplication.

useInterval - safe timer

A timer with setInterval requires cleanup and proper dependency handling. A custom hook encapsulates this logic:

function useInterval(callback, delay) {
  const savedCallback = useRef();

  // Remember the latest callback version
  useEffect(() => {
    savedCallback.current = callback;
  }, [callback]);

  // Set timer
  useEffect(() => {
    if (delay === null) return; // null = pause timer

    const tick = () => savedCallback.current();
    const id = setInterval(tick, delay);
    return () => clearInterval(id);
  }, [delay]);
}

// Usage
function MissionClock() {
  const [seconds, setSeconds] = useState(0);
  const [isRunning, setIsRunning] = useState(false);

  useInterval(() => {
    setSeconds(prev => prev + 1);
  }, isRunning ? 1000 : null); // null = pause

  return (
    <div>
      <p>Mission time: {seconds}s</p>
      <button onClick={() => setIsRunning(!isRunning)}>
        {isRunning ? 'Pause' : 'Start'}
      </button>
    </div>
  );
}

Thanks to useRef for the callback, the timer always calls the latest version of the function without needing to restart the interval.

useLocalStorage - persistent state

A hook that synchronizes state with localStorage:

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('Error writing to localStorage:', error);
    }
  }, [key, storedValue]);

  return [storedValue, setStoredValue];
}

// Usage - works like useState, but persists data
function ShipSettings() {
  const [theme, setTheme] = useLocalStorage('theme', 'dark');
  const [volume, setVolume] = useLocalStorage('volume', 50);

  return (
    <div>
      <select value={theme} onChange={e => setTheme(e.target.value)}>
        <option value="dark">Dark</option>
        <option value="light">Light</option>
      </select>
      <input
        type="range"
        value={volume}
        onChange={e => setVolume(Number(e.target.value))}
      />
    </div>
  );
}

After refreshing the page, settings are preserved - localStorage remembers values between sessions.

Rules for creating Custom Hooks

  1. Name starts with use - this is not optional. React requires this prefix to enforce hook rules
  2. Can call other hooks - useState, useEffect, useRef, and even other custom hooks
  3. Each call has its own state - two components using the same hook have independent copies of state
  4. Return what the component needs - can return values, arrays, objects, functions
// Custom Hook with multiple return values
function useToggle(initialValue = false) {
  const [value, setValue] = useState(initialValue);

  const toggle = () => setValue(prev => !prev);
  const setTrue = () => setValue(true);
  const setFalse = () => setValue(false);

  return { value, toggle, setTrue, setFalse };
}

// Usage
function ShieldControl() {
  const shields = useToggle(false);

  return (
    <div>
      <p>Shields: {shields.value ? 'ACTIVE' : 'DISABLED'}</p>
      <button onClick={shields.toggle}>Toggle</button>
      <button onClick={shields.setTrue}>Activate</button>
      <button onClick={shields.setFalse}>Deactivate</button>
    </div>
  );
}

Summary

Custom Hooks are one of the most powerful tools in React for code organization:

  1. Eliminate duplication - repeatable effect logic in one place
  2. Improve readability - components become shorter and more declarative
  3. Facilitate testing - hook logic can be tested independently from the component
  4. Are composable - custom hooks can call other custom hooks

Like modular spaceship systems - navigation system, communication system, defense system - each is a separate module (hook) that can be installed in any ship (component).

Code for this lesson: App.jsx
import React, { useState, useEffect, useRef } from 'react';

// Custom Hook: useToggle
function useToggle(initialValue = false) {
  const [value, setValue] = useState(initialValue);
  const toggle = () => setValue(prev => !prev);
  const setTrue = () => setValue(true);
  const setFalse = () => setValue(false);
  return { value, toggle, setTrue, setFalse };
}

// Custom Hook: useInterval
function useInterval(callback, delay) {
  const savedCallback = useRef();

  useEffect(() => {
    savedCallback.current = callback;
  }, [callback]);

  useEffect(() => {
    if (delay === null) return;
    const tick = () => savedCallback.current();
    const id = setInterval(tick, delay);
    return () => clearInterval(id);
  }, [delay]);
}

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

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

  return [storedValue, setStoredValue];
}

// Demo 1: useToggle
function ShieldControls() {
  const shields = useToggle(false);
  const weapons = useToggle(false);
  const engines = useToggle(true);

  return (
    <div className="demo-card">
      <h2>useToggle</h2>
      <div className="system-row">
        <span>Shields</span>
        <span className={shields.value ? 'on' : 'off'}>{shields.value ? 'ON' : 'OFF'}</span>
        <button onClick={shields.toggle}>Toggle</button>
      </div>
      <div className="system-row">
        <span>Weapons</span>
        <span className={weapons.value ? 'on' : 'off'}>{weapons.value ? 'ON' : 'OFF'}</span>
        <button onClick={weapons.toggle}>Toggle</button>
      </div>
      <div className="system-row">
        <span>Engines</span>
        <span className={engines.value ? 'on' : 'off'}>{engines.value ? 'ON' : 'OFF'}</span>
        <button onClick={engines.toggle}>Toggle</button>
      </div>
    </div>
  );
}

// Demo 2: useInterval
function MissionClock() {
  const [seconds, setSeconds] = useState(0);
  const isRunning = useToggle(false);

  useInterval(() => {
    setSeconds(prev => prev + 1);
  }, isRunning.value ? 1000 : null);

  const mins = String(Math.floor(seconds / 60)).padStart(2, '0');
  const secs = String(seconds % 60).padStart(2, '0');

  return (
    <div className="demo-card">
      <h2>useInterval</h2>
      <div className="clock">{mins}:{secs}</div>
      <div className="clock-controls">
        <button onClick={isRunning.toggle}>
          {isRunning.value ? 'Pause' : 'Start'}
        </button>
        <button onClick={() => { isRunning.setFalse(); setSeconds(0); }}>
          Reset
        </button>
      </div>
    </div>
  );
}

// Demo 3: useLocalStorage
function ShipSettings() {
  const [pilotName, setPilotName] = useLocalStorage('pilotName', '');
  const [theme, setTheme] = useLocalStorage('theme', 'dark');
  const [volume, setVolume] = useLocalStorage('volume', 50);

  return (
    <div className="demo-card">
      <h2>useLocalStorage</h2>
      <p className="hint">Data survives a page refresh!</p>
      <div className="setting">
        <label>Pilot:</label>
        <input
          value={pilotName}
          onChange={e => setPilotName(e.target.value)}
          placeholder="Enter name..."
        />
      </div>
      <div className="setting">
        <label>Theme:</label>
        <select value={theme} onChange={e => setTheme(e.target.value)}>
          <option value="dark">Dark</option>
          <option value="light">Light</option>
          <option value="blue">Cosmic</option>
        </select>
      </div>
      <div className="setting">
        <label>Volume: {volume}%</label>
        <input
          type="range"
          min="0"
          max="100"
          value={volume}
          onChange={e => setVolume(Number(e.target.value))}
        />
      </div>
    </div>
  );
}

function App() {
  return (
    <div className="app">
      <h1>Custom Hooks - Modular ship systems</h1>
      <div className="demos">
        <ShieldControls />
        <MissionClock />
        <ShipSettings />
      </div>
    </div>
  );
}

export default App;

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. Which of the following is NOT a typical use case for useEffect?

  2. 2. Which React hook replaces the componentDidMount method from class components?

Hands-on tasks in the game

  • Code editor

    Custom Media Query Hook

  • Code editor

    Battery Status Monitoring

  1. Coding taskPractice: useMediaQuery
  2. QuestionCommon useEffect Use Cases
  3. Coding taskPractice: Battery API
  4. QuestionLifecycle Method Mapping

Useful articles