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.
Common lifecycle use cases in 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.
useEffect(() => {
console.log('Component mounted');
}, []);count value changes.useEffect(() => {
console.log('Count changed:', count);
}, [count]);useEffect(() => {
const timer = setInterval(() => {
console.log('Tick');
}, 1000);
return () => clearInterval(timer);
}, []);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.
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;
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.
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.
Practice
useEffect hook in React functional components?Solution
Step 1: Understand the role of useEffect
TheuseEffecthook runs side effects like data fetching or timers after rendering.Step 2: Compare with other options
Declaring state is done withuseState, event handlers are functions, and styling is separate.Final Answer:
To run code after the component renders or updates -> Option CQuick Check:
useEffect runs side effects after render [OK]
- Confusing useEffect with useState
- Thinking useEffect is for styling
- Believing useEffect defines event handlers
Solution
Step 1: Understand dependency array in useEffect
An empty array[]means the effect runs once on mount only.Step 2: Analyze other options
Omitting dependencies runs effect after every render; arrays with unstable values like functions or objects run on every render since they are recreated.Final Answer:
useEffect(() => { console.log('Mounted'); }, []); -> Option BQuick Check:
Empty array runs effect once on mount [OK]
- Omitting dependency array causes repeated runs
- Using non-empty arrays runs effect multiple times
- Putting recreated functions or objects in dependency array causes re-runs
function Timer() {
const [count, setCount] = React.useState(0);
React.useEffect(() => {
const id = setInterval(() => {
setCount(c => c + 1);
}, 1000);
return () => clearInterval(id);
}, []);
return <div>Count: {count}</div>;
}What will be displayed after 3 seconds?
Solution
Step 1: Understand the interval effect
The effect sets an interval that increments count every 1000ms (1 second).Step 2: Calculate count after 3 seconds
After 3 intervals, count increments from 0 to 3.Final Answer:
Count: 3 -> Option DQuick Check:
Interval increments count every second [OK]
- Ignoring cleanup function
- Thinking count stays 0
- Confusing milliseconds with count value
useEffect(() => {
const timer = setTimeout(() => {
console.log('Hello');
}, 1000);
});Solution
Step 1: Check dependency array presence
Without a dependency array, the effect runs after every render, creating a new timeout each time.Step 2: Understand consequences
This causes multiple timers to accumulate (no cleanup returned), leading to multiple console.logs firing.Final Answer:
Missing dependency array causes multiple timeouts to be set on every render -> Option AQuick Check:
Missing dependencies cause repeated effect runs [OK]
- Thinking setTimeout is disallowed in useEffect
- Believing console.log can't be used
- Assuming timeout duration limits
userId prop changes in a React component. Which useEffect hook is correct?function UserProfile({ userId }) {
const [user, setUser] = React.useState(null);
useEffect(() => {
fetch(`https://api.example.com/users/${userId}`)
.then(res => res.json())
.then(data => setUser(data));
}, ???);
return <div>{user ? user.name : 'Loading...'}</div>;
}Solution
Step 1: Identify when to run the effect
The effect should run only whenuserIdchanges to fetch new data.Step 2: Choose correct dependency array
IncludinguserIdin the dependency array triggers effect on its change.Final Answer:
[userId] -> Option AQuick Check:
Dependency array controls when effect runs [OK]
- Using empty array runs effect only once
- Using state variable instead of prop
- Including functions like fetch in dependencies
Ready to prove it?
Pass the test and this pattern moves unknown
