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.
✦ 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.
Mark this lesson complete
Signed in, your progress follows you to every device.