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

Creating Custom Hooks - Advanced Patterns

6 min read ยท
In this lesson7

In the React cosmic fleet, one of the most valuable engineering skills is designing reusable modules. Imagine building navigation, communication, and diagnostic systems for hundreds of spaceships. Instead of writing each system from scratch for every ship, you create universal modules that can be connected to any vehicle. That's exactly how Custom Hooks work in React.

In the previous lesson, we learned the basics of custom hooks - useFetch, useInterval, useLocalStorage, and useToggle. Now we'll dive into advanced patterns, hook rules, and composition that will make your hooks truly professional.

Rules of Hooks

Before we start creating advanced hooks, we must know two fundamental rules, breaking which causes unpredictable errors:

Rule 1: Only call hooks at the top level

Hooks must always be called in the same order on every render. Never place hooks inside conditions, loops, or nested functions:

// BAD - hook inside condition
function SpaceShip({ hasRadar }) {
  if (hasRadar) {
    const [signal, setSignal] = useState(null); // ERROR!
  }
}

// GOOD - the condition inside the hook
function SpaceShip({ hasRadar }) {
  const [signal, setSignal] = useState(null);

  useEffect(() => {
    if (hasRadar) {
      // radar logic
    }
  }, [hasRadar]);
}

React tracks hooks based on their call order. If a condition causes one hook to be skipped, all subsequent hooks will have incorrect values - as if all the modules in the spaceship shifted positions.

Rule 2: Only call hooks from React components or custom hooks

You cannot call hooks from regular JavaScript functions. Only:

  • React functional components
  • Custom Hooks (functions starting with use)
// BAD - regular function
function calculateTrajectory() {
  const [speed] = useState(0); // ERROR!
}

// GOOD - custom hook
function useTrajectory() {
  const [speed, setSpeed] = useState(0);
  return { speed, setSpeed };
}

useDebounce - delaying actions

The useDebounce hook is extremely useful for real-time searching. Instead of sending an API request after every keystroke, we wait until the user finishes typing:

function useDebounce(value, delay) {
  const [debouncedValue, setDebouncedValue] = useState(value);

  useEffect(() => {
    const timer = setTimeout(() => {
      setDebouncedValue(value);
    }, delay);

    return () => clearTimeout(timer);
  }, [value, delay]);

  return debouncedValue;
}

// Usage - searching planets
function PlanetSearch() {
  const [query, setQuery] = useState('');
  const debouncedQuery = useDebounce(query, 500);

  useEffect(() => {
    if (debouncedQuery) {
      // Request sent only after 500ms pause in typing
      fetch(`/api/planets?search=${debouncedQuery}`);
    }
  }, [debouncedQuery]);

  return (
    <input
      value={query}
      onChange={e => setQuery(e.target.value)}
      placeholder="Search planets..."
    />
  );
}

The timer is cleared on every value change. Only when the user stops typing for 500ms will the value be updated and the API request sent.

usePrevious - remembering the previous value

This simple hook allows comparing the current value with the previous one:

function usePrevious(value) {
  const ref = useRef();

  useEffect(() => {
    ref.current = value;
  }, [value]);

  return ref.current;
}

// Usage - monitoring speed changes
function SpeedMonitor() {
  const [speed, setSpeed] = useState(0);
  const previousSpeed = usePrevious(speed);

  const trend = speed > previousSpeed
    ? 'Accelerating'
    : speed < previousSpeed
    ? 'Decelerating'
    : 'Constant speed';

  return <p>{trend}: {speed} km/s (was: {previousSpeed})</p>;
}

useArray - managing arrays

Arrays require specific operations (adding, removing, filtering). A custom hook encapsulates these operations in a clean interface:

function useArray(initialArray = []) {
  const [array, setArray] = useState(initialArray);

  const push = (element) => setArray(a => [...a, element]);
  const removeByIndex = (index) =>
    setArray(a => a.filter((_, i) => i !== index));
  const update = (index, newElement) =>
    setArray(a => a.map((item, i) => (i === index ? newElement : item)));
  const clear = () => setArray([]);
  const filter = (fn) => setArray(a => a.filter(fn));

  return { array, set: setArray, push, removeByIndex, update, clear, filter };
}

// Usage - crew list
function CrewManager() {
  const crew = useArray(['Captain Nova', 'Navigator Rex']);

  return (
    <div>
      {crew.array.map((member, i) => (
        <div key={i}>
          {member}
          <button onClick={() => crew.removeByIndex(i)}>Remove</button>
        </div>
      ))}
      <button onClick={() => crew.push('New member')}>
        Add crew member
      </button>
      <button onClick={crew.clear}>Dismiss crew</button>
    </div>
  );
}

Hook composition - combining modules

The true power of custom hooks reveals itself when we combine them with each other. Hooks can call other hooks, building complex behaviors from simple blocks:

// Hook 1: Simple state hook with validation
function useValidatedInput(initialValue, validator) {
  const [value, setValue] = useState(initialValue);
  const [error, setError] = useState(null);

  const handleChange = (newValue) => {
    setValue(newValue);
    const validationError = validator(newValue);
    setError(validationError);
  };

  return { value, error, onChange: handleChange, isValid: !error };
}

// Hook 2: Composition - form with multiple fields
function useSpaceshipForm() {
  const name = useValidatedInput('', (v) =>
    v.length < 3 ? 'Min. 3 characters' : null
  );
  const fuel = useValidatedInput(100, (v) =>
    v < 0 || v > 100 ? 'Range 0-100' : null
  );

  const isFormValid = name.isValid && fuel.isValid;

  const reset = () => {
    name.onChange('');
    fuel.onChange(100);
  };

  return { name, fuel, isFormValid, reset };
}

// Usage
function ShipRegistration() {
  const form = useSpaceshipForm();

  return (
    <form>
      <input
        value={form.name.value}
        onChange={e => form.name.onChange(e.target.value)}
      />
      {form.name.error && <span>{form.name.error}</span>}

      <input
        type="number"
        value={form.fuel.value}
        onChange={e => form.fuel.onChange(Number(e.target.value))}
      />
      {form.fuel.error && <span>{form.fuel.error}</span>}

      <button disabled={!form.isFormValid}>Register ship</button>
    </form>
  );
}

useSpaceshipForm uses useValidatedInput twice - each call creates an independent instance with its own state.

Pattern: useToggle, useCounter, useForm

Popular custom hook patterns worth knowing:

HookUse caseReturns
useToggleOn/off toggle{ value, toggle, setTrue, setFalse }
useCounterCounter with min/max{ count, increment, decrement, reset }
useFetchData fetching{ data, loading, error, refetch }
useDebounceDelaying valuesDelayed value
usePreviousPrevious valuePrevious value
useArrayArray operations{ array, push, remove, update, clear }
useLocalStoragePersistent state[value, setValue]

Summary

Custom Hooks are the foundation of a well-organized React application:

  1. Hook rules - always at the top level, only in components and hooks
  2. use prefix - mandatory, allows React to verify rules
  3. Composition - hooks can call other hooks, building complex behaviors
  4. Independent instances - each hook call has its own isolated state
  5. Reusability - one logic, many components

Like modular spaceship systems - each hook is a standalone module that can be installed, configured, and connected with other modules in any configuration.

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

// === useDebounce ===
function useDebounce(value, delay) {
  const [debouncedValue, setDebouncedValue] = useState(value);

  useEffect(() => {
    const timer = setTimeout(() => setDebouncedValue(value), delay);
    return () => clearTimeout(timer);
  }, [value, delay]);

  return debouncedValue;
}

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

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

// === useArray ===
function useArray(initialArray = []) {
  const [array, setArray] = useState(initialArray);
  const push = (el) => setArray(a => [...a, el]);
  const removeByIndex = (i) => setArray(a => a.filter((_, idx) => idx !== i));
  const clear = () => setArray([]);
  return { array, push, removeByIndex, clear, set: setArray };
}

// === 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 (e) { console.error(e); }
  }, [key, storedValue]);

  return [storedValue, setStoredValue];
}

// --- Demo Components ---

function DebounceDemo() {
  const [text, setText] = useState('');
  const debouncedText = useDebounce(text, 600);
  const [results, setResults] = useState([]);

  useEffect(() => {
    if (debouncedText) {
      const planets = ['Mercury','Venus','Earth','Mars','Jupiter','Saturn','Uranus','Neptune'];
      setResults(planets.filter(p =>
        p.toLowerCase().includes(debouncedText.toLowerCase())
      ));
    } else {
      setResults([]);
    }
  }, [debouncedText]);

  return (
    <div className="demo-card">
      <h3>useDebounce</h3>
      <input value={text} onChange={e => setText(e.target.value)} placeholder="Search for planets..." />
      <p className="hint">Debounced: "{debouncedText}"</p>
      {results.length > 0 && (
        <ul className="results">{results.map(r => <li key={r}>{r}</li>)}</ul>
      )}
    </div>
  );
}

function PreviousDemo() {
  const [speed, setSpeed] = useState(0);
  const prevSpeed = usePrevious(speed);

  const trend = speed > (prevSpeed || 0) ? 'Accelerating' :
                speed < (prevSpeed || 0) ? 'Braking' : 'Constant speed';

  return (
    <div className="demo-card">
      <h3>usePrevious</h3>
      <p className="speed-display">{speed} km/s</p>
      <p className="hint">Previously: {prevSpeed ?? 0} km/s | {trend}</p>
      <div className="btn-row">
        <button onClick={() => setSpeed(s => s + 10)}>+10</button>
        <button onClick={() => setSpeed(s => Math.max(0, s - 10))}>-10</button>
        <button onClick={() => setSpeed(0)}>Reset</button>
      </div>
    </div>
  );
}

function ToggleDemo() {
  const shields = useToggle(false);
  const engines = useToggle(true);

  return (
    <div className="demo-card">
      <h3>useToggle</h3>
      <div className="toggle-item">
        <span>Shields: <b style={{color: shields.value ? '#2ecc71' : '#e74c3c'}}>
          {shields.value ? 'ACTIVE' : 'DISABLED'}
        </b></span>
        <button onClick={shields.toggle}>Toggle</button>
      </div>
      <div className="toggle-item">
        <span>Engines: <b style={{color: engines.value ? '#2ecc71' : '#e74c3c'}}>
          {engines.value ? 'ACTIVE' : 'DISABLED'}
        </b></span>
        <button onClick={engines.toggle}>Toggle</button>
      </div>
    </div>
  );
}

function ArrayDemo() {
  const crew = useArray(['Captain Nova', 'Navigator Rex']);
  const [name, setName] = useState('');

  const addMember = () => {
    if (name.trim()) { crew.push(name.trim()); setName(''); }
  };

  return (
    <div className="demo-card">
      <h3>useArray</h3>
      <div className="crew-list">
        {crew.array.map((member, i) => (
          <div key={i} className="crew-member">
            <span>{member}</span>
            <button onClick={() => crew.removeByIndex(i)} className="btn-small">X</button>
          </div>
        ))}
      </div>
      <div className="add-row">
        <input value={name} onChange={e => setName(e.target.value)}
          placeholder="Crew member name..." onKeyDown={e => e.key === 'Enter' && addMember()} />
        <button onClick={addMember}>Add</button>
      </div>
      <button onClick={crew.clear} className="btn-danger">Release the crew</button>
    </div>
  );
}

function StorageDemo() {
  const [theme, setTheme] = useLocalStorage('space-theme', 'dark');
  const [volume, setVolume] = useLocalStorage('space-volume', 50);

  return (
    <div className="demo-card">
      <h3>useLocalStorage</h3>
      <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="cosmic">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>
      <p className="hint">Values saved in localStorage</p>
    </div>
  );
}

export default function App() {
  return (
    <div className="app">
      <h1>Custom Hooks - Spaceship modules</h1>
      <div className="grid">
        <DebounceDemo />
        <PreviousDemo />
        <ToggleDemo />
        <ArrayDemo />
        <StorageDemo />
      </div>
    </div>
  );
}

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. Why can you NOT call hooks inside conditional statements (if/else)?

  2. 2. How does a custom hook differ from a regular JavaScript function?

These are 2 of 3 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Code editor

    Create a custom hook useDebounce(value, delay) returning a debounced value and useToggle(initialValue) returning { value, toggle, setTrue, setFalse }. Both hooks should work with the test components on the page.

  • Vertical ordering

    Order the steps for creating a custom hook from start to finish:

  • Code editor

    Create a custom hook useArray(initialArray) returning { array, set, push, removeByIndex, update, clear, filter } and usePrevious(value) returning the previous value. The hooks should work with the crew management component on the page.

  • Click in order

    Arrange the useDebounce custom hook syntax in the correct order:

  • Code editor

    Build a comprehensive Saturn Ring Observatory Control Panel containing: useEffect for monitoring various ring orbital phases, useLayoutEffect for real-time measurement synchronization, cleanup functions for proper sensor unmounting, dependency arrays for precise re-run control, multiple effects for independent monitoring systems (RingA, RingB, RingC monitoring), effect optimization patterns, async effects for data fetching from space probes, and conditional effects responding to different observatory states. Create a monitoring system worthy of the most advanced Saturn ring observatory!

  1. QuestionRules of Hooks in React
  2. QuestionCustom Hook vs JavaScript Function
  3. Coding taskPractice: useDebounce and useToggle
  4. QuestionState in Custom Hooks
  5. Put in orderSteps to Create a Custom Hook
  6. Coding taskPractice: useArray and usePrevious
  7. Click in orderuseDebounce Custom Hook Syntax
  8. Coding taskProject: Saturn Ring Monitor
  9. Project to submitMentor Project: Time Monitoring Center
  10. VideoVideo: Module Summary

Useful articles