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

useInterval

Published 📅: ....
Last modified 📝: ....
Location 📍: 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

React

Server Side Rendering Compatible CSS Theming

Published: ....

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

Resetting Controlled Components in Forms

Published: ....

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

Request for a (minimal) RSC Framework

Published: ....

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

Don't Break the Implicit Prop Contract

Published: ....

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

A Better useSSR Implementation

Published: ....

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

React Error Boundaries: Revisited

Published: ....

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

Suspense Plus GraphQL

Published: ....

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

Managing Complex UI Component State

Published: ....

A few thoughts on managing complex UI component state within React

Understanding React 16.3 Updates

Published: ....

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