0
0
Reactframework~30 mins

Lifecycle mapping with hooks in React - Mini Project: Build & Apply

Choose your learning style9 modes available
Lifecycle mapping with hooks
📖 Scenario: You are building a simple React component that tracks and displays the number of times a button is clicked. You want to learn how to use React hooks to map lifecycle events like mounting, updating, and unmounting.
🎯 Goal: Create a React functional component called ClickTracker that uses useState to count clicks and useEffect to log messages when the component mounts, updates, and unmounts.
📋 What You'll Learn
Create a state variable count initialized to 0
Create a useEffect hook that logs 'Component mounted' once when the component first renders
Create a useEffect hook that logs 'Count updated' every time count changes
Create a useEffect hook that logs 'Component unmounted' when the component is removed
Render a button that increments count when clicked
Display the current count value in a <p> element
💡 Why This Matters
🌍 Real World
React components often need to run code when they appear, update, or disappear. This project shows how to map those lifecycle events using hooks.
💼 Career
Understanding React lifecycle with hooks is essential for building modern web apps and is a common skill required in frontend developer roles.
Progress0 / 4 steps
1
Set up state for click count
Create a React functional component called ClickTracker. Inside it, use the useState hook to create a state variable named count initialized to 0.
React
Need a hint?

Use const [count, setCount] = useState(0); inside your component function.

2
Add mount lifecycle logging with useEffect
Inside the ClickTracker component, add a useEffect hook that logs the message 'Component mounted' to the console only once when the component first renders.
React
Need a hint?

Use useEffect with an empty dependency array [] to run code only once on mount.

3
Add update lifecycle logging for count changes
Add another useEffect hook inside ClickTracker that logs 'Count updated' to the console every time the count state changes.
React
Need a hint?

Use useEffect with [count] as dependency to run code when count changes.

4
Add unmount logging and button to update count
Complete the ClickTracker component by adding a useEffect hook that logs 'Component unmounted' when the component is removed. Also, render a button that increments count when clicked and a paragraph that displays the current count.
React
Need a hint?

Use a cleanup function inside useEffect to log on unmount. Render a button with onClick that calls setCount(count + 1). Display count inside a paragraph.