0
0
Reactframework~30 mins

Effect execution timing in React - Mini Project: Build & Apply

Choose your learning style9 modes available
Effect Execution Timing in React
📖 Scenario: You are building a simple React component that tracks a count and shows when effects run during the component lifecycle. This helps understand when React runs side effects.
🎯 Goal: Create a React functional component that uses useEffect to log messages at different times: after every render, only once on mount, and when the count changes.
📋 What You'll Learn
Create a state variable count initialized to 0
Add a useEffect that runs after every render and logs 'Effect runs after every render'
Add a useEffect that runs only once on mount and logs 'Effect runs once on mount'
Add a useEffect that runs only when count changes and logs 'Effect runs when count changes'
Render a button that increments count when clicked
💡 Why This Matters
🌍 Real World
Understanding when effects run helps you manage side effects like data fetching, subscriptions, or animations in React apps.
💼 Career
React developers must control effect timing to optimize performance and avoid bugs related to stale data or unnecessary updates.
Progress0 / 4 steps
1
Set up state variable count
Create a React functional component called EffectTiming. Inside it, use useState to create a state variable called count initialized to 0.
React
Need a hint?

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

2
Add effect that runs after every render
Inside the EffectTiming component, add a useEffect hook without dependencies that logs the string 'Effect runs after every render' to the console.
React
Need a hint?

Use useEffect(() => { console.log('Effect runs after every render'); }); without a dependency array.

3
Add effect that runs only once on mount
Add another useEffect hook inside EffectTiming that logs 'Effect runs once on mount' to the console. Make sure it runs only once when the component mounts by passing an empty dependency array.
React
Need a hint?

Use useEffect(() => { console.log('Effect runs once on mount'); }, []); to run once on mount.

4
Add effect that runs when count changes and a button to update count
Add a third useEffect hook that logs 'Effect runs when count changes' to the console. It should run only when count changes, so pass [count] as the dependency array. Also, add a button inside the returned JSX that increments count by 1 when clicked.
React
Need a hint?

Use useEffect(() => { console.log('Effect runs when count changes'); }, [count]); and add a button with onClick={() => setCount(count + 1)}.