📖 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
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
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
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
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.
Practice
(1/5)
1. Which React hook is used to run code after a component renders, replacing lifecycle methods like componentDidMount and componentDidUpdate?
easy
A. useEffect
B. useState
C. useContext
D. useRef
Solution
Step 1: Understand lifecycle replacement
The useEffect hook runs code after rendering, replacing lifecycle methods like componentDidMount and componentDidUpdate.
Step 2: Identify the correct hook
useState manages state, useContext accesses context, and useRef stores mutable values. Only useEffect runs side effects after render.
Final Answer:
useEffect -> Option A
Quick Check:
Effect hook = useEffect [OK]
Hint: useEffect runs code after render like lifecycle methods [OK]
Common Mistakes:
Confusing useState with useEffect
Thinking useRef runs effects
Believing useContext triggers after render
2. Which of the following is the correct syntax to run an effect only once when a React component mounts using useEffect?
easy
A. useEffect(() => { /* code */ }, null);
B. useEffect(() => { /* code */ });
C. useEffect(() => { /* code */ }, true);
D. useEffect(() => { /* code */ }, []);
Solution
Step 1: Understand dependency array usage
Passing an empty array [] as the second argument to useEffect makes it run only once after the first render (component mount).
Step 2: Analyze each option
useEffect(() => { /* code */ }); runs after every render. useEffect(() => { /* code */ }, true); runs after every render since non-array dependencies are ignored. useEffect(() => { /* code */ }, null); with null also runs after every render as it's not an array.
Final Answer:
useEffect(() => { /* code */ }, []); -> Option D
Quick Check:
Empty array = run once [OK]
Hint: Empty dependency array runs effect once on mount [OK]
Common Mistakes:
Omitting dependency array causes effect every render
Using null instead of empty array
Passing non-array values like true or null as dependencies
3. What will be logged to the console when the following React component mounts and then the count state changes?
C. Logs 'Count is 0' on mount and 'Count is 1' after first click
D. Logs nothing because useEffect has dependencies
Solution
Step 1: Understand useEffect with dependency
The effect runs after the component mounts and whenever count changes because count is in the dependency array.
Step 2: Trace the console logs
On mount, count is 0, so it logs 'Count is 0'. After clicking the button, count becomes 1, triggering the effect again and logging 'Count is 1'.
Final Answer:
Logs 'Count is 0' on mount and 'Count is 1' after first click -> Option C
Quick Check:
Effect runs on mount and dependency change [OK]
Hint: Effect runs on mount and when dependencies change [OK]
Common Mistakes:
Thinking effect runs only once without dependencies
Assuming no logs because dependencies exist
Confusing useEffect with setInterval
4. Identify the problem in this React component that uses useEffect and suggest the fix:
function Timer() {
React.useEffect(() => {
const id = setInterval(() => console.log('Tick'), 1000);
}, []);
return <div>Timer</div>;
}
medium
A. No problem; code works fine as is
B. Missing cleanup function to clear the interval on unmount
C. Dependency array should include 'id' to update interval
D. setInterval should be replaced with setTimeout
Solution
Step 1: Analyze effect side effects
The effect sets an interval but does not clear it, causing a memory leak when the component unmounts.
Step 2: Suggest cleanup function
Return a cleanup function from useEffect that calls clearInterval(id) to stop the interval on unmount.
Final Answer:
Missing cleanup function to clear the interval on unmount -> Option B
Quick Check:
Cleanup prevents memory leaks [OK]
Hint: Always clean intervals/timeouts in useEffect cleanup [OK]
Common Mistakes:
Forgetting to clear intervals causing leaks
Adding dependencies unnecessarily
Replacing setInterval with setTimeout incorrectly
5. You want to fetch user data only once when a component mounts and cancel the fetch if the component unmounts before it finishes. Which is the best way to implement this using useEffect?