• Home
  • Blog
  • Projects
  • Bookshelf
  • About
← Back to all snippets

useInterval

Published ....
Last modified ....
From Netarts, OR

Share this snippet on BlueskySee discussion on Bluesky


import { useState, useEffect, useRef } from "react";

export function useInterval(callback, delay) {
  const savedCallback = useRef();

  // Remember the latest callback.














useEffect(() => {
savedCallback.current = callback;
}, [callback]);
// Set up the interval.
useEffect(() => {
function tick() {
savedCallback.current();
}
if (delay !== null) {
let id = setInterval(tick, delay);
return () => clearInterval(id);
}
}, [delay]);
}

Originally sourced from Dan Abramov's blog


Tags:

snippetReact

Loading...

Related Posts

snippet

Progressive Identifiers

....

Quick Git

....

Multi-step Native HTML Forms

....

Git Co-Authorship

....

React

Multi-step Native HTML Forms

....

Server Side Rendering Compatible CSS Theming

....

A quick tip to implementing CSS theming that's compatible with Server Side Rendered applications!

Resetting Controlled Components in Forms

....

A quick way to handle resetting internal state in components when a parent form is submitted!

Request for a (minimal) RSC Framework

....

Some features and functionality that I'd like within a React Server Component compatible framework.

Don't Break the Implicit Prop Contract

....

React components have a fundamental contract that is often unstated in their implementation, and you should know about it!

A Better useSSR Implementation

....

Replace that old useState and useEffect combo for a new and better option!

React Error Boundaries: Revisited

....

Revising my previous blog post on React Error Boundaries and my preferred go-to implementation!

Suspense Plus GraphQL

....

A few thoughts on using Suspense with GraphQL to optimize application data loading

Managing Complex UI Component State

....

A few thoughts on managing complex UI component state within React

Understanding React 16.3 Updates

....

A quick overview of the new lifecycle methods introduced in React 16.3