0
0
Reactframework~3 mins

Why Multiple effects in a component in React? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how splitting your component's tasks into multiple effects can save you from tangled code and hidden bugs!

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
useEffect(() => { fetchData(); document.title = 'Page'; window.addEventListener('resize', handleResize); return () => window.removeEventListener('resize', handleResize); }, []);
After
useEffect(() => { fetchData(); }, []);
useEffect(() => { document.title = 'Page'; }, []);
useEffect(() => { window.addEventListener('resize', handleResize); return () => window.removeEventListener('resize', handleResize); }, []);
What It Enables

This makes your component easier to read, maintain, and extend with multiple independent tasks running smoothly.

Real Life Example

Think of a dashboard app that loads user info, updates notifications, and tracks window size changes separately but all inside one component.

Key Takeaways

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.