Created
          July 30, 2020 06:29 
        
      - 
      
- 
        Save ospfranco/8a23054197b7817f9e367637819d0f98 to your computer and use it in GitHub Desktop. 
    ReactJS hook for setting interval
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | export function useInterval (callback: () => void, delay: number) { | |
| const savedCallback = useRef() | |
| // Remember the latest callback. | |
| useEffect(() => { | |
| savedCallback.current = callback | |
| }, [callback]) | |
| // Set up the interval. | |
| useEffect(() => { | |
| function tick () { | |
| if (savedCallback.current) { | |
| savedCallback.current() | |
| } | |
| } | |
| if (delay !== null) { | |
| const id = setInterval(tick, delay) | |
| return () => clearInterval(id) | |
| } | |
| }, [delay]) | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment