useEffect
Some code should run after the component appears, for example loading data or starting a timer. Use the useEffect hook for this.
A component's main job is to return JSX. But apps also need to talk to the outside world: fetch products from a server, set the page title, start a timer, listen to window size. These are called side effects. Doing them directly in the component body would run them on every render (possibly in a loop), so React gives you useEffect to run them at the right moment.
React.useEffect(() => {
// runs after the component appears
}, []); // [] = run only onceThe array at the end lists the values the effect depends on. With [] it runs once. With [city] it runs again whenever city changes.
The dependency array is how you tell React when to run the effect again. A common example: a weather widget with a city state - when the user picks a new city, the effect runs again and fetches new weather. Forgetting a dependency leads to stale data; adding too many can cause extra requests, so list exactly the values the effect uses.
<!DOCTYPE html>
<html>
<body>
<div id="root"></div>
<script src="https://unpkg.com/react@18.3.1/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@18.3.1/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone@7.24.7/babel.min.js"></script>
<script type="text/babel">
function Clock() {
const [time, setTime] = React.useState(new Date().toLocaleTimeString());
React.useEffect(() => {
const timer = setInterval(() => {
setTime(new Date().toLocaleTimeString());
}, 1000);
return () => clearInterval(timer); // clean up when the component goes away
}, []);
return <h2>Sale ends soon! Time now: {time}</h2>;
}
function App() {
return <Clock />;
}
ReactDOM.createRoot(document.getElementById("root")).render(<App />);
</script>
</body>
</html>▶ Try it yourselfuseEffectruns side effects after rendering.- The dependency array controls when it runs again.
- Return a cleanup function to stop timers or requests.
