DEV Community


useUpdateEffect: useEffect that doesn't trigger on mount

hnrq profile image Henrique Ramos ・1 min read

Since its debut in 2018, React Hooks introduced useEffect: a Hook that adds lifecycle to functional components. As the wiki says: We can think of it as componentDidMount, componentDidUpdate, and componentWillUnmount combined. It can be called only on the initial render by providing an empty array, but, what if we want it not to be called when mounted? Enter: useUpdateEffect.

The code behind it is very simple. It only takes a useRef, to keep track of the initial render, and a useEffect with a guard to check whether if it's the first mount or not:

const useUpdateEffect: typeof useEffect = (effect, deps) => {
  const isFirstMount = useRef(true);

  useEffect(() => {
    if (!isFirstMount.current) effect();
    else isFirstMount.current = false;
  }, deps);
Enter fullscreen mode Exit fullscreen mode

Some of you may be asking: "Why useRef?". Well, because it persists its value across renders and doesn't trigger a re-render. useState, on the other side, would make the component be re-rendered, which is not the desired behavior.

And here's a (classic) example of a counter button!

Discussion (0)

Editor guide