0
0
Reactframework~30 mins

Unmounting phase in React - Mini Project: Build & Apply

Choose your learning style9 modes available
React Component Unmounting Phase
📖 Scenario: You are building a simple React app that shows a message when a component is visible. When the component is removed from the screen, you want to run some cleanup code to log a message.
🎯 Goal: Create a React functional component that displays a message. Add a button to toggle showing or hiding this component. Use the unmounting phase to log a message when the component is removed.
📋 What You'll Learn
Create a React functional component called Message that returns a <div> with the text 'Hello, I am here!'.
Create a state variable called showMessage in the main component to control if Message is shown.
Add a button that toggles showMessage between true and false.
Use useEffect with a cleanup function inside Message to log 'Message component is unmounting' when it is removed.
💡 Why This Matters
🌍 Real World
React components often need to clean up resources like timers or subscriptions when they are removed from the screen to avoid bugs or memory leaks.
💼 Career
Understanding the unmounting phase is essential for React developers to manage component lifecycle and resource cleanup properly.
Progress0 / 4 steps
1
Create the Message component
Create a React functional component called Message that returns a <div> with the text 'Hello, I am here!'.
React
Need a hint?

Define a function named Message that returns a <div> with the exact text.

2
Add state to toggle Message visibility
In the App component, create a state variable called showMessage using useState and set its initial value to true.
React
Need a hint?

Import useState and create showMessage with initial value true.

3
Add button to toggle Message display
Inside the App component's return, add a <button> that toggles showMessage between true and false when clicked. Also, conditionally render the Message component only when showMessage is true.
React
Need a hint?

Add a button with an onClick that flips showMessage. Render <Message /> only if showMessage is true.

4
Add cleanup in Message unmounting phase
Inside the Message component, use useEffect to add a cleanup function that logs 'Message component is unmounting' when the component is removed from the screen.
React
Need a hint?

Use useEffect with an empty dependency array and return a cleanup function that logs the message.