I have to monitoring some data update info on the screen each one or two seconds. The way I figured that was using this implementation:
componentDidMount() {
Although an old question it was the top result when I searched for React Polling and didn't have an answer that worked with Hooks.
// utils.js import React, { useState, useEffect, useRef } from 'react'; export const useInterval = (callback, delay) => { const savedCallback = useRef(); useEffect(() => { savedCallback.current = callback; }, [callback]); useEffect(() => { function tick() { savedCallback.current(); } if (delay !== null) { const id = setInterval(tick, delay); return () => clearInterval(id); } }, [delay]); }
Source: https://overreacted.io/making-setinterval-declarative-with-react-hooks/
You can then just import and use.
// MyPage.js
import useInterval from '../utils';
const MyPage = () => {
useInterval(() => {
// put your interval code here.
}, 1000 * 10);
return my page content;
}