CPCODELAB
React

Custom Hooks

11 min read

Extracting Reusable Logic

A custom hook is a function whose name starts with use and that calls other hooks inside. They're the primary way to share stateful logic between components — without changing component structure or introducing extra components.

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

// Reusable data-fetching hook
function useFetch(url) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    let cancelled = false;
    setLoading(true);
    fetch(url)
      .then(r => r.json())
      .then(d => { if (!cancelled) { setData(d); setLoading(false); } })
      .catch(e => { if (!cancelled) { setError(e); setLoading(false); } });
    return () => { cancelled = true; };
  }, [url]);

  return { data, loading, error };
}

// Usage
function CourseDetail({ courseId }) {
  const { data: course, loading, error } = useFetch(`/api/courses/${courseId}`);
  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error loading course.</p>;
  return <h1>{course.title}</h1>;
}

Custom hooks are the foundation of reusable React code. At CPCODELAB, you'll build a library of custom hooks throughout the course to handle auth state, local storage persistence, debounced inputs, and more.

Each call to a custom hook gets its own isolated state. Two components calling useFetch with different URLs maintain completely separate data, loading, and error states.

Ready to test yourself?
Practice React— quiz & coding exercises