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.