DEV Community

Discussion on: Why useeffect is running twice in react

Collapse
 
brense profile image
Rense Bakker

Its worth noting that in React 18 when you run in dev mode with React.StrictMode on. Your useEffect hook will always run atleast twice because your component is mounted twice.

Collapse
 
elias102 profile image
Elias

Thanks for this good note ❤️

Collapse
 
cestabhi profile image
Abhishek Mhatre

Thanks. I finally figured out why it was running twice.

Collapse
 
jahid6597 profile image
MD. JAHID HOSSAIN

glad to know ❤️

Collapse
 
jahid6597 profile image
MD. JAHID HOSSAIN

Yes, when using React.StrictMode in development, your components will be rendered twice, causing useEffect hooks to run twice. This can cause unexpected behavior and should be taken into consideration when writing your code. However, this behavior is specific to development and will not occur in production.

Collapse
 
brense profile image
Rense Bakker

Indeed, its a good test to see if your useEffect hooks do something bad, like not cleanup subscriptions or event listeners.

Thread Thread
 
jahid6597 profile image
MD. JAHID HOSSAIN

Using useEffect in React requires proper cleanup to avoid memory leaks and unexpected behavior. This can be achieved by returning a cleanup function in the useEffect callback, which is executed by React when the component is unmounted. The cleanup function should also include any necessary cleanup procedures for external libraries, such as event listeners or subscriptions.

import React, { useEffect, useState } from 'react';

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

  useEffect(() => {
    const interval = setInterval(() => 
        setCount(c => c + 1), 
    1000);

    return () => clearInterval(interval);
  }, []);

  return (
    <div>{count}</div>
  );
}
Enter fullscreen mode Exit fullscreen mode

In this example, the useEffect hook sets up an interval that increments the count in every second, and returns a cleanup function that clears the interval when the component is unmounted. This ensures that the interval is not still running and affecting performance or causing memory leaks when the component is no longer in use.

Thread Thread