React Hooks Deep Dive
useState, useEffect, useRef, useContext, useReducer, and custom hooks patterns.
Overview
Hooks let you use state and other React features in function components without writing classes.
Key Concepts
- useState — Manages local component state
- useEffect — Handles side effects like data fetching and subscriptions
- useRef — Accesses DOM elements and persists mutable values
- useReducer — Manages complex state logic with reducers
- useContext — Consumes context values without nested consumers
Code Examples
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
const abortRef = useRef(null);
useEffect(() => {
abortRef.current = new AbortController();
fetch(`/api/users/${userId}`, { signal: abortRef.current.signal })
.then(res => res.json())
.then(data => { setUser(data); setLoading(false); });
return () => abortRef.current?.abort();
}, [userId]);
if (loading) return <p>Loading...</p>;
return <h1>{user.name}</h1>;
}
Practice
Build a data fetching component with loading states and cleanup on unmount.