Skip to main content

Lesson 11 of 11

Practice & Quiz - React Hooks Deep Dive

Test your mastery of useEffect, useRef, useMemo, useCallback, and useReducer with a practical data-fetching hook exercise and 5 quiz questions.

10 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Practical Exercise - useFetch Custom Hook with Abort

Practical Exercise - useFetch Custom Hook with Abort
import { useState, useEffect, useRef, useCallback } from 'react';

// Production-grade useFetch - demonstrates useEffect cleanup, useRef, useCallback
interface FetchState<T> {
  data: T | null;
  loading: boolean;
  error: string | null;
}

function useFetch<T>(url: string): FetchState<T> & { refetch: () => void } {
  const [state, setState] = useState<FetchState<T>>({
    data: null, loading: true, error: null,
  });
  const abortRef = useRef<AbortController | null>(null);
  const [trigger, setTrigger] = useState(0);

  useEffect(() => {
    // Cleanup: abort previous in-flight request
    abortRef.current?.abort();
    const controller = new AbortController();
    abortRef.current = controller;

    setState(prev => ({ ...prev, loading: true, error: null }));

    fetch(url, { signal: controller.signal })
      .then(res => {
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        return res.json() as Promise<T>;
      })
      .then(data => setState({ data, loading: false, error: null }))
      .catch(err => {
        if (err.name === 'AbortError') return; // ignore cancellations
        setState({ data: null, loading: false, error: err.message });
      });

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

  // useCallback - stable reference (doesn't trigger parent re-renders)
  const refetch = useCallback(() => setTrigger(t => t + 1), []);

  return { ...state, refetch };
}

// Usage
interface Post { id: number; title: string; body: string; }

function PostViewer({ postId }: { postId: number }) {
  const { data, loading, error, refetch } = useFetch<Post>(
    `https://jsonplaceholder.typicode.com/posts/${postId}`
  );

  if (loading) return <p>Loading...</p>;
  if (error)   return <p style={{ color: 'red' }}>Error: {error} <button onClick={refetch}>Retry</button></p>;
  return (
    <article>
      <h2>{data?.title}</h2>
      <p>{data?.body}</p>
      <button onClick={refetch}>Refresh</button>
    </article>
  );
}

Module Quiz

Module Quiz
Question 1 of 5

A useEffect with NO dependency array runs:

Tip

Tip

Practice Practice Quiz React Hooks Deep Dive in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagramโ€ฆ

Modern React: Use Hooks instead of class lifecycle methods

Practice Task

Note

Practice Task - (1) Write a working example of Practice Quiz React Hooks Deep Dive from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with Practice Quiz React Hooks Deep Dive is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/11 done