DEV Community

Cover image for How to clean up useEffect's code
Gustavo
Gustavo

Posted on

2

How to clean up useEffect's code

What is useEffect?

| "useEffect is a React Hook that lets you synchronize a component with an external system." - react.dev

So, whenever there is something on screen we want to update when another variable changes, we can use useEffect. But be careful, always think twice before using it.

How to clean it up

  • you can return a function inside useEffect's first parameter, so it runs after the main code is executed
  • this was really useful for me when I was coding a pomodoro-like app to know wether to update or interrupt the amounts of seconds past
useEffect(() => {
  if (activeCycle) {
    const interval = setInterval(() => {
      const secondsDifference = differenceInSeconds(
        new Date(),
        activeCycle.startedAt
      );

      if (secondsDifference >= totalSeconds) {
        // interrupt the cycle code
        // ...

        clearInterval(interval);
      } else {
        // update the amount of seconds past in the current cycle
        // ...
      }
    }, 1000);
  }
}, [activeCycle, totalSeconds]);
Enter fullscreen mode Exit fullscreen mode
  • in this example, I needed a way to close the intervals, since useEffect created a new interval each time it executed and this interval kept executing every time
    • so the timer was basically not working as it should.
  • for it to work, I needed to clean up every execution
  • that's the result:
useEffect(() => {
  let interval: number;

  if (activeCycle) {
    interval = setInterval(() => {
      const secondsDifference = differenceInSeconds(
        new Date(),
        activeCycle.startedAt
      );

      if (secondsDifference >= totalSeconds) {
        // interrupt the cycle code
        // ...

        clearInterval(interval);
      } else {
        // update the amount of seconds past in the current cycle
        // ...
      }
    }, 1000);
  }
  return () => {
    clearInterval(interval);
  };
}, [activeCycle, totalSeconds]);
Enter fullscreen mode Exit fullscreen mode
  • I declared interval before, so I could clear it on the setup function

Reference


If you have any doubts or advice, feel free to leave a comment or ping me on Twitter

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post →

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay