Search code examples
reactjsuse-effect

How can I let the useEffect run only when its parameter change?


The useEffect run in the first and when the parameter change is run another one, I don't want the use effect run until the parameter change only. How?


Solution

  • You can use hook like this to check it's first mount/render

    const useDidMountEffect = (func, deps) => {
        const didMount = useRef(false);
    
        useEffect(() => {
            if (didMount.current) func();
            else didMount.current = true;
        }, deps);
    }
    

    Next you can check result ot useDidMountEffect