Discover how splitting your component's tasks into multiple effects can save you from tangled code and hidden bugs!
Why Multiple effects in a component in React? - Purpose & Use Cases
Imagine you have a webpage where you want to fetch data, update the page title, and listen for window resizing all at once.
Doing all these tasks manually means mixing different code parts together, making it hard to keep track.
When you try to handle all these tasks in one place, your code becomes messy and confusing.
It's easy to forget to clean up event listeners or update things at the right time, causing bugs and slow performance.
React lets you split these tasks into separate effects inside one component.
Each effect runs independently and cleans up after itself, keeping your code clear and reliable.
useEffect(() => { fetchData(); document.title = 'Page'; window.addEventListener('resize', handleResize); return () => window.removeEventListener('resize', handleResize); }, []);useEffect(() => { fetchData(); }, []);
useEffect(() => { document.title = 'Page'; }, []);
useEffect(() => { window.addEventListener('resize', handleResize); return () => window.removeEventListener('resize', handleResize); }, []);This makes your component easier to read, maintain, and extend with multiple independent tasks running smoothly.
Think of a dashboard app that loads user info, updates notifications, and tracks window size changes separately but all inside one component.
Handling multiple tasks in one effect leads to messy code.
Splitting tasks into multiple effects keeps code clean and bug-free.
Each effect manages its own setup and cleanup independently.
Practice
useEffect hooks in a React component?Solution
Step 1: Understand the purpose of multiple useEffect hooks
MultipleuseEffecthooks allow you to separate different side effects logically in a component.Step 2: Recognize the benefit of separation
This separation makes the component easier to read and maintain because each effect handles a specific task.Final Answer:
It separates different side effects for better readability and maintenance. -> Option BQuick Check:
Multiple effects = separation and clarity [OK]
- Thinking multiple effects combine tasks into one
- Believing multiple effects prevent re-renders
- Assuming multiple effects auto-optimize performance
useEffect hooks in a React functional component?Solution
Step 1: Recall correct useEffect syntax
TheuseEffecthook takes a function and a dependency array as arguments, separated by a comma.Step 2: Identify correct separation of two hooks
Two separateuseEffecthooks should be called one after another, each with its own function and dependency array, ending with semicolons.Final Answer:
useEffect(() => { /* effect 1 */ }, []); useEffect(() => { /* effect 2 */ }, []); -> Option AQuick Check:
Separate hooks with own deps and semicolons [OK]
- Using commas instead of semicolons between hooks
- Combining dependency arrays incorrectly
- Omitting dependency arrays causing unwanted runs
function Example({ count }) {
useEffect(() => {
console.log('Effect A:', count);
}, [count]);
useEffect(() => {
console.log('Effect B: component mounted');
}, []);
return <div>Count: {count}</div>;
}What will be logged when the component first mounts with
count = 5?Solution
Step 1: Understand useEffect execution order on mount
AlluseEffecthooks run after the first render. They run in the order they appear in code.Step 2: Identify the order of console logs
The firstuseEffectlogs 'Effect A: 5', the second logs 'Effect B: component mounted'. So logs appear in code order.Final Answer:
Effect A: 5
Effect B: component mounted -> Option DQuick Check:
Effects run in code order on mount [OK]
- Assuming effects run in reverse order
- Thinking effects run before render
- Confusing dependency arrays impact on first run
function Demo({ value }) {
useEffect(() => {
console.log('Effect 1:', value);
}, [value]);
useEffect(() => {
console.log('Effect 2');
});
return <div>Value: {value}</div>;
}Solution
Step 1: Check dependency arrays in useEffect hooks
The firstuseEffecthas a dependency array [value], so it runs only when value changes.Step 2: Analyze second useEffect without dependency array
The seconduseEffecthas no dependency array, so it runs after every render, which might be unintended.Final Answer:
The second useEffect has no dependency array, so it runs after every render. -> Option CQuick Check:
Missing deps means effect runs every render [OK]
- Thinking multiple useEffects are not allowed
- Ignoring missing dependency arrays
- Believing console.log is invalid inside useEffect
useEffect hooks?Solution
Step 1: Separate concerns with multiple useEffect hooks
Fetching data should happen once on mount, so useEffect with empty dependency array is best.Step 2: Update document title when user.name changes
Use a separate useEffect with [user.name] dependency to update title only when name changes.Final Answer:
Use two separate useEffect hooks: one with empty deps for fetch, one with [user.name] for title. -> Option AQuick Check:
Separate effects by task and dependencies [OK]
- Combining unrelated tasks in one effect
- Missing dependencies causing stale updates
- Running fetch on every render unintentionally
Ready to prove it?
Pass the test and this pattern moves unknown
