DEV Community

Ali
Ali

Posted on • Edited on

How to use setInterval in React hooks

Problem: Any code/function called inside setInterval does not show updated state (where state is created using useState hook). The reason is any function passed in setInterval is a closure and values of all its arguments or variables accessables inside it (variables defined in outer functions) become static and take the snapshot of data at the time of the interval creation and does not look back at the original variables again.
Solution
One better solution, a custom hook, to use setInterval with React hooks is provided by Dan Abramov's at his personal blog (article linked below). The is as below:

import React, { useState, useEffect, useRef } from 'react';

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]);
}

Here is the how to use it in your code demo

Reference
Original article at Dan Abramov blog

Top comments (3)

Collapse
 
andreirobertooleniuc profile image
Andrei Roberto Oleniuc

thank you man you solved this stupid problem

Collapse
 
prog585 profile image
Ali

My pleasure

Collapse
 
maparrar profile image
Alejandro Parra

It works, thank you!