Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

My React Component is rendering twice because of Strict Mode

My React Component is rendering twice. So, I decided to do a line by line debug and the problem is here

 if ( workInProgress.mode & StrictMode) {
        instance.render();
      }

React-dom.development.js

Is it because of strict mode? can I disable it? What is Strict mode? Do I need it?

like image 463
Marry Joanna Avatar asked Apr 16 '20 15:04

Marry Joanna


People also ask

Why is React functional component rendering twice?

React will soon provide a new Concurrent Mode which will break render work into multiple parts. Pausing and resuming the work between this parts should avoid the blocking of the browsers main thread. This means that the render phase could be invoked multiple times and should be a Pure Function without any side effects!


4 Answers

StrictMode renders components twice (on dev but not production) in order to detect any problems with your code and warn you about them (which can be quite useful).

If you have StrictMode enabled in your app but don't remember enabling it, it might be because you used create-react-app or similar to create your app initially, which automatically enables StrictMode by default.

For example, you might find that your {app} is wrapped by <React.StrictMode> in your index.js:

  ReactDOM.render(
     <React.StrictMode>
       {app}
     </React.StrictMode>,
    document.getElementById('root')
  );

If so, you can disable StrictMode by removing the <React.StrictMode> tag:

  ReactDOM.render(
    {app}
    document.getElementById('root')
  );
like image 121
rangfu Avatar answered Oct 17 '22 15:10

rangfu


Yes you have to remove Strict mode as

Strict mode can't automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following functions: Class component constructor , render , and shouldComponentUpdate methods.

Source: React Docs: Strict Mode

like image 38
Haris Shafiq Avatar answered Oct 17 '22 15:10

Haris Shafiq


For Next.js user here like my-self, strict mode is also enabled by default and causes this issue.

You can disable it in this way

// next.config.js
module.exports = {
  reactStrictMode: false,
}
like image 34
sgoran Avatar answered Oct 17 '22 17:10

sgoran


It seems the component renders twice, but the first rendered component is not unmounted? At least that is the behaviour I'm seeing with React 17, might a bug in my code of course

like image 1
Ziriax Avatar answered Oct 17 '22 15:10

Ziriax