What are React Hooks?
Hooks let you use state and lifecycle features in functional components — no class components needed.
useState — Local State
jsx
const [count, setCount] = useState(0);
const [user, setUser] = useState({ name: "", email: "" });
// Always create new objects — never mutate directly
setUser(prev => ({ ...prev, name: "Ali" }));useEffect — Side Effects
jsx
// Runs once on mount
useEffect(() => {
document.title = "My App";
}, []);
// Runs when 'id' changes
useEffect(() => {
fetchUser(id);
}, [id]);
// Cleanup on unmount
useEffect(() => {
const timer = setInterval(tick, 1000);
return () => clearInterval(timer); // cleanup
}, []);useRef — DOM Access & Mutable Values
jsx
const inputRef = useRef(null);
// Auto-focus on mount
useEffect(() => { inputRef.current?.focus(); }, []);
// Store interval ID without causing re-render
const timerRef = useRef(null);
timerRef.current = setInterval(tick, 1000);useContext — Global State
jsx
const ThemeContext = createContext("light");
// Provider
<ThemeContext.Provider value="dark">
<App />
</ThemeContext.Provider>
// Consumer
const theme = useContext(ThemeContext);Custom Hooks — Reusable Logic
jsx
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
fetch(url)
.then(r => r.json())
.then(setData)
.catch(setError)
.finally(() => setLoading(false));
}, [url]);
return { data, loading, error };
}
// Usage
const { data, loading } = useFetch("/api/courses");The key rule: hooks must always be called at the top level — never inside conditions or loops.
Published by Sohail Code Academy
Share