DEV Community

Henrique Ramos
Henrique Ramos

Posted on

4 1

useUpdateEffect: useEffect that doesn't trigger on mount

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!

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay