React hooks useEffect only on update?

前端 未结 8 953
予麋鹿
予麋鹿 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:40

    Both Shubham and Mario suggest the right approach, however the code is still incomplete and does not consider following cases.

    1. If the component unmounts, it should reset it's flag
    2. The passing effect function may have a cleanup function returned from it, that would never get called

    Sharing below a more complete code which covers above two missing cases:

    import React from 'react';
    
    const useIsMounted = function useIsMounted() {
      const isMounted = React.useRef(false);
    
      React.useEffect(function setIsMounted() {
        isMounted.current = true;
    
        return function cleanupSetIsMounted() {
          isMounted.current = false;
        };
      }, []);
    
      return isMounted;
    };
    
    const useUpdateEffect = function useUpdateEffect(effect, dependencies) {
      const isMounted = useIsMounted();
      const isInitialMount = React.useRef(true);
    
      React.useEffect(() => {
        let effectCleanupFunc = function noop() {};
    
        if (isInitialMount.current) {
          isInitialMount.current = false;
        } else {
          effectCleanupFunc = effect() || effectCleanupFunc;
        }
        return () => {
          effectCleanupFunc();
          if (!isMounted.current) {
            isInitialMount.current = true;
          }
        };
      }, dependencies); // eslint-disable-line react-hooks/exhaustive-deps
    };
    

提交回复
热议问题