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.
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
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.
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.
Finished this lesson?