Lifecycle methods help you run code at specific times in a component's life. This lets you set up, update, or clean up things smoothly.
0
0
Common lifecycle use cases in React
Introduction
Load data from a server when a component appears on the screen.
Set up a timer or interval when a component starts and clear it when it stops.
Listen for window size changes and update the layout accordingly.
Clean up subscriptions or event listeners when a component is removed.
Run code only once when the component first shows.
Syntax
React
useEffect(() => {
// code to run on mount or update
return () => {
// cleanup code runs on unmount or before update
};
}, [dependencies]);useEffect runs after the component renders.
The dependencies array controls when the effect runs again.
Examples
This runs only once when the component first appears.
React
useEffect(() => {
console.log('Component mounted');
}, []);This runs every time the
count value changes.React
useEffect(() => {
console.log('Count changed:', count);
}, [count]);This sets up a timer when the component mounts and clears it when it unmounts.
React
useEffect(() => {
const timer = setInterval(() => {
console.log('Tick');
}, 1000);
return () => clearInterval(timer);
}, []);Sample Program
This component counts seconds after it appears. It starts a timer that updates the count every second. When the component disappears, it stops the timer to avoid problems.
React
import React, { useState, useEffect } from 'react'; function Timer() { const [seconds, setSeconds] = useState(0); useEffect(() => { const interval = setInterval(() => { setSeconds(s => s + 1); }, 1000); return () => clearInterval(interval); }, []); return ( <div> <p>Seconds passed: {seconds}</p> </div> ); } export default Timer;
OutputSuccess
Important Notes
Always clean up timers or listeners in the return function to avoid memory leaks.
Empty dependency array [] means the effect runs only once on mount.
Adding variables to dependencies makes the effect run when those variables change.
Summary
useEffect lets you run code at key moments in a component's life.
Use it to load data, set timers, or clean up resources.
Remember to manage dependencies and cleanup carefully.