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)
thank you man you solved this stupid problem
My pleasure
It works, thank you!