What if your app could handle loading and cleanup perfectly without you lifting a finger?
Why Common lifecycle use cases in React? - Purpose & Use Cases
Imagine you build a web app where you must fetch data, update the page, and clean up resources manually every time a user visits or leaves a page.
Manually tracking when to load data or clean up is tricky and easy to forget. This causes bugs, slow updates, and wasted memory.
React lifecycle hooks let you run code exactly when components appear, update, or disappear, keeping your app smooth and bug-free.
window.onload = () => fetchData(); window.onunload = () => cleanup();
useEffect(() => {
fetchData();
return () => cleanup();
}, []);You can easily manage data loading, event listeners, and cleanup tied to component life, making apps reliable and efficient.
Loading user info when a profile page opens and stopping background timers when leaving keeps your app fast and responsive.
Manual resource handling is error-prone and hard to maintain.
React lifecycle hooks automate running code at the right time.
This leads to cleaner, faster, and more reliable apps.
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
