Multiple effects in a component
📖 Scenario: You are building a simple React component that shows a user's name and the current window width. You want to update the document title with the user's name and also update the width value whenever the window is resized.
🎯 Goal: Create a React functional component that uses two separate useEffect hooks: one to update the document title with the user's name, and another to listen for window resize events and update the width state.
📋 What You'll Learn
Create a state variable
name with initial value 'Alice'.Create a state variable
width with initial value equal to window.innerWidth.Use one
useEffect to update document.title to `User: ${name}` whenever name changes.Use another
useEffect to add a resize event listener on window that updates width state, and clean up the listener on unmount.Render the
name and width values inside <div> elements.💡 Why This Matters
🌍 Real World
Many React apps need to handle multiple side effects like updating the page title and responding to window size changes separately.
💼 Career
Understanding multiple useEffect hooks is essential for React developers to manage side effects cleanly and avoid bugs.
Progress0 / 4 steps