Category: Next.js, React and TypeScript

React: setInterval Creates Duplicate Requests After Switching Tabs

Read this guide in Polish

Each reopening of the panel leads to another timer and an increasing number of API requests. The effect is created by the interval, but does not slow it down when the component is dependent or unmounted.

How to identify the source of the problem

Check the number of active timers in the component profile and whether the request frequency increases upon re-entry. See cleanup returned by useEffect and those values on which the frequency of query depends.

Compare the message from the console with the result of the production compilation and the condition after the page has been refreshed.

Repair steps

Return clearInterval(id) from the effect, and hold the polling if not needed when hiding the view. In addition to the interval, make sure that you cancel your pending requests so that the older answer does not update the outdated view.

How to Test Solution

Upon multiple switching of the panel, one timer or none inactive is visible.

Security and restrictions

Do not create setInterval directly in the component body during each render.