📖 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
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
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
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
Hint
Return a function inside useEffect that calls clearInterval(timerId);.
Practice
(1/5)
1. What is the primary purpose of the useEffect hook in React functional components?
easy
A. To define event handlers
B. To declare state variables
C. To run code after the component renders or updates
D. To style components dynamically
Solution
Step 1: Understand the role of useEffect
The useEffect hook runs side effects like data fetching or timers after rendering.
Step 2: Compare with other options
Declaring state is done with useState, event handlers are functions, and styling is separate.
Final Answer:
To run code after the component renders or updates -> Option C
Quick Check:
useEffect runs side effects after render [OK]
Hint: useEffect runs code after render or update [OK]
Common Mistakes:
Confusing useEffect with useState
Thinking useEffect is for styling
Believing useEffect defines event handlers
2. Which of the following is the correct syntax to run an effect only once when a React component mounts?
easy
A. useEffect(() => { console.log('Mounted'); });
B. useEffect(() => { console.log('Mounted'); }, []);
C. useEffect(() => { console.log('Mounted'); }, [() => {}]);
D. useEffect(() => { console.log('Mounted'); }, [{}]);
Solution
Step 1: Understand dependency array in useEffect
An empty array [] means the effect runs once on mount only.
Step 2: Analyze other options
Omitting dependencies runs effect after every render; arrays with unstable values like functions or objects run on every render since they are recreated.
Final Answer:
useEffect(() => { console.log('Mounted'); }, []); -> Option B
Quick Check:
Empty array runs effect once on mount [OK]
Hint: Empty dependency array means run once on mount [OK]
Common Mistakes:
Omitting dependency array causes repeated runs
Using non-empty arrays runs effect multiple times
Putting recreated functions or objects in dependency array causes re-runs