React Hooks replaced class components. Functional, composable, simpler — and with a few gotchas.
Basic Hooks¶
import { useState, useEffect } from ‘react’;
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch(/api/users/${userId})
.then(r => r.json())
.then(data => { setUser(data); setLoading(false); });
}, [userId]); // Dependency array!
if (loading) return
Loading…
; return
React Hooks Tutorial¶
; }
Custom Hook¶
function useFetch(url) { const [data, setData] = useState(null); const [error, setError] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { fetch(url) .then(r => r.json()) .then(setData) .catch(setError) .finally(() => setLoading(false)); }, [url]); return { data, error, loading }; } // Usage const { data: users, loading } = useFetch(‘/api/users’);
Key Takeaway¶
useState for state, useEffect for side effects, custom hooks for reuse. The dependency array is key.