DEV Community

Discussion on: Why useeffect is running twice in react

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