Discover how React's useEffect saves you from endless manual updates and bugs!
What is useEffect in React - Why It Matters
Imagine you want to update the page every time a user clicks a button or when data loads from the internet. You try to write code that watches for these changes and updates the page manually.
Manually tracking changes and updating the page is tricky and easy to forget. You might miss updates or cause bugs by updating too often or too late. It becomes a mess as your app grows.
useEffect lets React automatically run your code when something changes, like data loading or user actions. It keeps your app in sync without you having to watch everything yourself.
componentDidMount() { fetchData(); }
componentDidUpdate(prevProps) { if (prevProps.id !== this.props.id) fetchData(); }useEffect(() => { fetchData(); }, [id]);It enables you to run code at the right time, keeping your app responsive and clean without extra hassle.
Loading user info from a server whenever the user ID changes, so the page always shows the right data.
Manually syncing code with changes is hard and error-prone.
useEffect runs code automatically when dependencies change.
This keeps your app updated and easier to manage.
Practice
useEffect in React?Solution
Step 1: Understand what
useEffectdoesuseEffectruns code after the component renders or when specified data changes.Step 2: Compare with other React features
State variables declare data, styling is CSS, and creating components is unrelated touseEffect.Final Answer:
To run code after the component renders or when data changes -> Option CQuick Check:
useEffect runs code after render or data change [OK]
- Confusing useEffect with useState
- Thinking useEffect styles components
- Believing useEffect creates components
useEffect that runs only once after the first render?Solution
Step 1: Identify how to run useEffect once
Passing an empty array[]as dependency makesuseEffectrun only once after the first render.Step 2: Check other options
Without dependencies (useEffect(() => { console.log('Hello'); });), it runs after every render. Options B and C pass non-array values, causing the effect to run after every render (with a React warning).Final Answer:
useEffect(() => { console.log('Hello'); }, []); -> Option BQuick Check:
Empty dependency array means run once [OK]
- Omitting dependency array causes repeated runs
- Passing non-array values thinking it runs once
- Confusing [] with null or true
import React, { useState, useEffect } from 'react';
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log('Count is:', count);
}, [count]);
return (
<button onClick={() => setCount(count + 1)}>Increment</button>
);
}Solution
Step 1: Understand useEffect with [count] dependency
The effect runs after first render and every timecountchanges, logging the current count.Step 2: Analyze button click behavior
Clicking the button increasescount, triggering useEffect to log the new value.Final Answer:
Logs 'Count is: 0' and then logs updated count each time button clicked -> Option AQuick Check:
useEffect runs on count change, logging each update [OK]
- Thinking useEffect runs only once without empty array
- Believing no logs happen without empty array
- Assuming infinite loops without setCount inside useEffect
useEffect:useEffect(() => {
fetchData();
}, fetchData);Assume
fetchData is a function defined outside.Solution
Step 1: Check dependency argument type
The second argument touseEffectmust be an array listing dependencies, not a function.Step 2: Identify correct syntax
It should be[fetchData]iffetchDatais a dependency, not justfetchDataalone.Final Answer:
Dependency array should be an array, not a function -> Option DQuick Check:
useEffect dependencies must be an array [OK]
- Passing a function instead of an array as dependencies
- Ignoring dependency array causing repeated runs
- Thinking useEffect cannot call functions
useEffect pattern is correct?useEffect(() => {
const subscription = subscribeToUserData();
fetchUserData();
return () => {
subscription.unsubscribe();
};
}, []);Solution
Step 1: Check dependency array usage
Empty array[]ensures effect runs once on mount and cleanup on unmount.Step 2: Verify cleanup function correctness
Returning a function that unsubscribes cleans up resources properly when component unmounts.Final Answer:
This pattern correctly fetches once and cleans up on unmount -> Option AQuick Check:
Empty array + cleanup function = run once + cleanup [OK]
- Omitting cleanup function causing memory leaks
- Not using empty array causing repeated fetches
- Placing subscription inside cleanup function incorrectly
Ready to prove it?
Pass the test and this pattern moves unknown
