Cleanup, and When Not to Use an Effect

Cleanup. Return a function and React runs it before the next effect and once more when the component goes away. Anything you started, stop here.

Try it

Delete the return () => clearInterval(id) line, then toggle the timer off and on a few times. The number starts climbing in jumps, because every old interval is still running.

loading editor…

loading React…

✦ React runs effects twice in development, on purpose

It mounts, unmounts and remounts each component once so that a missing cleanup shows up immediately rather than as a slow leak in production. It is not a bug and you should not work around it. If double running breaks something, that something needed cleanup.

When not to use an effect. If you can calculate the value during the render, do that. An effect that only transforms data costs an extra render and briefly displays the wrong thing first.

An effect responding to a click should usually just be the click handler. Ask what outside system this synchronizes with. If the answer is none, it is not an effect.

◈ Graded Component

Build a component with a button (id step) that increases a count, shown in an element with id count. Use an effect to keep an element with id doubled showing twice the count. Then explain to yourself why this is the wrong use of an effect, and make doubled a plain calculation instead. The checks require the calculated version: doubled must be correct in the very same render as count, with no lag.

Checked against what your component renders and how it responds, not against how you wrote it. 3 visible and 1 hidden check.

loading editor…

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Practice Test →
← Back