Complete Guide to React Hooks: useState & useEffect (React 19)
Learn how to manage local reactive state and synchronize side effects in modern functional React components.
Concepts & Theory
`useState` declares a reactive state variable. Invoking its setter schedules a re-render with the updated value.
`useEffect` synchronizes components with external systems like network APIs, timers, and browser event listeners.
The dependency array dictates when effects execute: empty `[]` runs once on mount; dependencies `[id]` run on change.
Returning a cleanup function from `useEffect` tears down active listeners or intervals, preventing memory leaks.
Code Example
Run in Playgroundimport React, { useState, useEffect } from "react";
export function Chronometre({ dureeMax = 60 }) {
const [secondes, setSecondes] = useState(0);
const [actif, setActif] = useState(false);
useEffect(() => {
if (!actif) return;
// Démarre l'intervalle
const timer = setInterval(() => {
setSecondes((prev) => {
if (prev >= dureeMax) {
setActif(false);
return prev;
}
return prev + 1;
});
}, 1000);
// Fonction de nettoyage cruciale pour éviter les fuites mémoire
return () => clearInterval(timer);
}, [actif, dureeMax]);
return (
<div className="p-4 rounded-xl border border-cyan-500/30">
<h3 className="text-lg font-bold">Chronomètre : {secondes}s</h3>
<button
onClick={() => setActif(!actif)}
className="mt-2 px-4 py-2 bg-cyan-500 text-black font-bold rounded"
>
{actif ? "Pause" : "Démarrer"}
</button>
</div>
);
}Common Pitfalls & Mistakes
✗ Omitting dependencies from useEffect
useEffect(() => {
console.log(userId);
}, []);useEffect(() => {
console.log(userId);
}, [userId]);Omitting reactive values creates stale closure bugs where the effect reads outdated state snapshots.
Frequently Asked Questions
When should functional state updates setVal(prev => prev + 1) be used?▾
Always use functional updates when the next state depends on current state to guarantee fresh values during batched updates.
Master React with interactive exercises
Complete hands-on code challenges in your browser with real-time feedback and progressive hints.
