React hooks useEffect only on update?

前端 未结 8 972
予麋鹿
予麋鹿 2020-12-12 18:53

If we want to restrict useEffect to run only when the component mounts, we can add second parameter of useEffect with [].



        
8条回答
  •  一个人的身影
    2020-12-12 19:35

    I really like Shubham's response, so I made it a custom Hook

    /**
     * A custom useEffect hook that only triggers on updates, not on initial mount
     * Idea stolen from: https://stackoverflow.com/a/55075818/1526448
     * @param {Function} effect
     * @param {Array} dependencies
     */
    export default function useUpdateEffect(effect, dependencies = []) {
      const isInitialMount = useRef(true);
    
      useEffect(() => {
        if (isInitialMount.current) {
          isInitialMount.current = false;
        } else {
          effect();
        }
      }, dependencies);
    }
    

提交回复
热议问题