Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

React

Peter Mingione
Peter Mingione
11,870 Points

useEffect question ...

Laura says ...

When we refresh the page, we see that 'running side effect' is logged to the console. Which is what we expect, since the side effect function runs after the first render.

But since isRunning is set to false then shouldn't we skip the setInterval function and then run:

console.log('Clean Up')

1 Answer

Travis Alstrand
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Travis Alstrand
Treehouse Project Reviewer

Great question Peter Mingione! These things still boggle my brain and it takes me a while to really break things down.

On page refresh, the component starts fresh — so React runs the effect for the first time. You see "Running side effect" because the effect runs, but "clean up" doesn't appear yet because there's nothing to clean up — the cleanup only runs before the next effect or when the component is unmounted.

Here's a step-by-step of the process that I hope helps.

When the page is refreshed

  • The whole React app reloads.

  • The Stopwatch component mounts fresh.

  • React initializes state:

    • isRunning = false
    • elapsedTime = 0
  • React renders the JSX.

  • Then it runs the useEffect for the first time:

    • Logs "Running side effect"
    • Skips the setInterval because isRunning is false
    • Returns a cleanup function — but React doesn’t call it yet.

So you only see: "Running side effect"

Why we don't see "clean up" on refresh

  • Because the previous effect never existed — this is the first run of useEffect after a fresh mount.

  • The cleanup function only runs:

    • Before the next run of the effect (if isRunning changes)
    • Or when the component unmounts

On a hard refresh, there was no previous effect to clean up — so no cleanup to do yet.