File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1- import { useEffect } from "react" ;
1+ import { useEffect , useRef } from "react" ;
22
33type UseIntervalOptions = {
44 /** If passed, will refresh every interval MS */
@@ -16,12 +16,19 @@ export function useInterval({
1616 disabled = false ,
1717 callback,
1818} : UseIntervalOptions ) {
19+ // Always keep the latest callback in a ref so the effects below
20+ // never close over a stale version.
21+ const latestCallback = useRef ( callback ) ;
22+ useEffect ( ( ) => {
23+ latestCallback . current = callback ;
24+ } , [ callback ] ) ;
25+
1926 // On interval
2027 useEffect ( ( ) => {
2128 if ( ! interval || interval <= 0 || disabled ) return ;
2229
2330 const intervalId = setInterval ( ( ) => {
24- callback ( ) ;
31+ latestCallback . current ( ) ;
2532 } , interval ) ;
2633
2734 return ( ) => clearInterval ( intervalId ) ;
@@ -33,7 +40,7 @@ export function useInterval({
3340
3441 const handleFocus = ( ) => {
3542 if ( document . visibilityState === "visible" ) {
36- callback ( ) ;
43+ latestCallback . current ( ) ;
3744 }
3845 } ;
3946
@@ -50,7 +57,7 @@ export function useInterval({
5057
5158 // On load
5259 useEffect ( ( ) => {
53- if ( disabled ) return ;
54- callback ( ) ;
55- } , [ ] ) ;
60+ if ( disabled || ! onLoad ) return ;
61+ latestCallback . current ( ) ;
62+ } , [ disabled , onLoad ] ) ;
5663}
You can’t perform that action at this time.
0 commit comments