How to prevent inline functions from binding to old state values

后端 未结 2 624
梦毁少年i
梦毁少年i 2021-01-20 03:27

In a project with React components using hooks, I am trying to understand how to properly avoid calling callbacks that are bound to old state values. The below example illus

2条回答
  •  野性不改
    2021-01-20 04:07

    You can put this in it's own hook also. I have this in my production code

    /**
     * A react hook for setting up an interval
     * @param handler - Function to execute on interval
     * @param interval - interval in milliseconds
     * @param runImmediate - If the function is executed immediately
     */
    export const useInterval = (handler: THandlerFn, interval: number | null, runImmediate = false): void => {
      const callbackFn = useRef()
    
      // Update callback function
      useEffect((): void => {
        callbackFn.current = handler
      }, [handler])
    
      // Setup interval
      useEffect((): (() => void) | void => {
        const tick = (): void => {
          callbackFn.current && callbackFn.current()
        }
    
        let timerId: number
        if (interval) {
          if (runImmediate) {
            setTimeout(tick, 0)
          }
    
          timerId = setInterval(tick, interval)
    
          return (): void => {
            clearInterval(timerId)
          }
        }
      }, [interval, runImmediate])
    }
    

提交回复
热议问题