Build a useInterval Hook

Write the code, see it run, pass the checks.

The problem

  • hard
  • Code
  • Pro

Write a custom hook and export it by name: useInterval(callback, delay) calls callback every delay milliseconds while the component is mounted; the first call comes after one delay, not straight away. When delay is null the interval is paused, and changing delay to a number starts it again at that speed. When the component re-renders with a new callback function, later calls go to the newest one, and the timer keeps its rhythm instead of starting over, so a component that re-renders often still ticks. Unmounting stops it. The default export App is a timer with a pause button for the preview; the checks test useInterval itself with delays of 20 to 60 milliseconds.

Your code must pass

  • Calls the callback every delay milliseconds
  • A null delay pauses it
  • Calls the newest callback
  • Keeps ticking while the component re-renders often
  • Stops when unmounted