With useEffect, how can I skip applying an effect upon the initial render?

As the guide states,

The Effect Hook, useEffect, adds the ability to perform side effects from a function component. It serves the same purpose as componentDidMount, componentDidUpdate, and componentWillUnmount in React classes, but unified into a single API.

In this example from the guide it’s expected that count is 0 only on initial render:

const [count, setCount] = useState(0);

So it will work as componentDidUpdate with additional check:

useEffect(() => {
  if (count)
    document.title = `You clicked ${count} times`;
}, [count]);

This is basically how custom hook that can be used instead of useEffect may work:

function useDidUpdateEffect(fn, inputs) {
  const didMountRef = useRef(false);

  useEffect(() => {
    if (didMountRef.current) { 
      return fn();
    }
    didMountRef.current = true;
  }, inputs);
}

Credits go to @Tholle for suggesting useRef instead of setState.

Leave a Comment