Reactjs – React hooks useEffect only on update

react-hooksreactjs

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

useEffect(() => {
  // ...
}, []);

But how can we make useEffect to run only when the moment when the component is updated except initial mount?

Best Answer

If you want the useEffect to run only on updates except initial mount, you can make use of useRef to keep track of initialMount with useEffect without the second parameter.

const isInitialMount = useRef(true);

useEffect(() => {
  if (isInitialMount.current) {
     isInitialMount.current = false;
  } else {
      // Your useEffect code here to be run on update
  }
});