useTimeout() React Hook

James Fulford
Nov 29, 2019 · 2 min read
Running out of time! Photo by Brad Neathery on Unsplash

Working with time effects in React is hard. For example, building countdown components is incredibly easy to do wrong if the React component lifecycle is used incorrectly (but can be easy, if you get a useTime hook!).

The same difficulty goes for integrating delayed callbacks into the React lifecycle. We’re going to wrap setTimeout in a React Hook. In this article, we’re going to discuss:

  • handling callbacks in React Hooks
  • effect cleanup
  • canceling an effect

Code First!

The hook, Jest tests, and an example component can be found on a GitHub repo:

Provided a callback and a timeout number (in milliseconds), the hook will start a setTimeout for that many milliseconds and return a function that can cancel the timeout.

Interesting fact, in case you were wondering: calling clearTimeout on an ID that has already been cleared, is a no-op. No worries if you cancel an already-completed task.

Hook Dependencies and Effect Cleanup

The trickiest part of using this hook has to do with when you specify callbacks. If during a re-render the callback passed to useTimeout is re-defined (even if the implementation is identical), then the effect cleanup is triggered. This would cause the timeout to be canceled and a new timeout would be queued. This might not be the behavior you want.

To control the re-render reschedule behavior, you should use React’s useCallback and manage dependencies there. When your callback’s dependencies change, the callback will change and trigger the timeout cleanup/re-render then.

When it comes to managing Rect Hook dependencies properly, I suggest the exhaustive-deps eslint rule.

Sample Usage

I put together a quick StackBlitz to show off a sample component using this hook.

The component shows off the re-render behavior of the hook, with and without the useCallback approach. It also shows off the cancellation callback. Make sure you open console and read the comments!

Also, check out the unit tests in the GitHub repo: they make it quite clear how the hook acts.

Related Articles

Interested in learning more about React Hooks? Check out this recent article from yours truly:

JavaScript in Plain English

Learn the web's most important programming language.

James Fulford

Written by

Harvard. Tech Lead. American.

JavaScript in Plain English

Learn the web's most important programming language.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade