The useEffect
hook in React allows you to perform side effects in functional components. You can use it for operations such as data fetching, direct DOM manipulation, subscriptions, and other actions that are not related to rendering the component.
Basic usage of useEffect
:
import React, { useState, useEffect } from 'react'; function ExampleComponent() { const [count, setCount] = useState(0); useEffect(() => { document.title = `You clicked ${count} times`; }, [count]); // Only re-runs when count changes return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}>Click me</button> </div> ); }
Cleaning up an effect: Effects can return a cleanup function that runs when the component unmounts or before re-running the effect.
useEffect(() => { const timer = setInterval(() => { console.log('This will run every second!'); }, 1000); return () => clearInterval(timer); // Cleanup function }, []); // Empty dependency array, effect runs once
The useEffect
hook should be used when you need to perform operations after rendering the component or when you need to synchronize the component with external systems.