Practical technology learning
React Effects: Pair a Timer Setup with Its Matching Cleanup
A timer can outlive the component behavior that created it unless its lifecycle is deliberate. This small React practice task pairs one interval setup with its own cleanup. Use a local counter and keep the observation separate from any claim about precise timer scheduling.
Describe the external process
The component displays a count and receives a delay value. The external process is an interval that requests count updates. Write down the intended lifetime: start while the component is mounted, replace the interval when its delay changes, and stop it when the component is removed.
Keep the handle with its setup
Inside useEffect, obtain an interval handle from setInterval. Its callback can use setCount(current => current + 1). Return a cleanup function that calls clearInterval with the handle created by that particular setup. Include the reactive delay in the dependency list instead of suppressing the dependency linter.
Rehearse a dependency change
Start the component, change the delay and then remove the component. For a changed dependency, React invokes the old cleanup before the new setup. On removal, it invokes cleanup again for the active setup. Record which handle each cleanup stops; an unrelated global handle can stop the wrong interval.
Use development behavior as evidence
Development Strict Mode can run an additional setup/cleanup cycle to stress-test symmetry. A correct setup and cleanup should tolerate that sequence. Do not add a guard merely to hide the repeated observation. Record the environment and actual lifecycle trace before deciding that a second setup is a production duplicate.
Check the small contract
- No interval creation during rendering.
- Each cleanup stops the interval created by its corresponding setup.
- Changing the delay does not leave the previous interval running.
- A removed component has no intended active timer.
Keep the conclusion bounded
Timers are not precision clocks, and observing tick counts alone is a weak cleanup test. Inspect the lifecycle directly in your local exercise. Components, hooks and state foundations are within the Mango Engineers React learning path; use the trace to discuss ownership of external processes.