0
0
Reactframework~30 mins

Common lifecycle use cases in React - Mini Project: Build & Apply

Choose your learning style9 modes available
Common lifecycle use cases in React
📖 Scenario: You are building a simple React component that shows a counter. You want to learn how to set up initial data, configure a timer, update the counter every second, and clean up the timer when the component is removed.
🎯 Goal: Build a React functional component called Counter that starts counting from zero, increases the count every second, and stops the timer when the component is unmounted.
📋 What You'll Learn
Use React functional components with hooks
Use useState to hold the counter value
Use useEffect to set up and clean up the timer
Increment the counter every second
Clear the timer when the component unmounts
💡 Why This Matters
🌍 Real World
Timers and counters are common in apps like clocks, games, quizzes, and live data displays.
💼 Career
Understanding React lifecycle with hooks is essential for building interactive and efficient user interfaces.
Progress0 / 4 steps
1
Set up the initial counter state
Create a React functional component called Counter. Inside it, use useState to create a state variable called count with initial value 0.
React
Need a hint?

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

2
Configure a timer interval
Inside the Counter component, use useEffect to set up a timer that runs every 1000 milliseconds (1 second). For now, just create the timer with setInterval and store its ID in a variable called timerId.
React
Need a hint?

Use useEffect with an empty dependency array to run once. Inside it, create const timerId = setInterval(() => { }, 1000);.

3
Update the counter every second
Inside the setInterval callback, update the count state by increasing it by 1 using setCount. Use the function form of setCount to get the latest value.
React
Need a hint?

Use setCount(prevCount => prevCount + 1); inside the setInterval callback.

4
Clean up the timer on unmount
Inside the useEffect, return a cleanup function that calls clearInterval with the timerId to stop the timer when the component unmounts.
React
Need a hint?

Return a function inside useEffect that calls clearInterval(timerId);.