Reputation: 2793
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 the strict mode? Can I disable it? What is Strict Mode? Do I need it?
Upvotes: 278
Views: 191771
Reputation: 16189
if you are using nextjs and you want to disable strict mode go to your next.config.js
file and set reactStrictMode to false
module.exports = {
reactStrictMode: false,
};
but strict mode is recommended for development once you check if the double mount is caused by stric mode it's preferable to enable it
Upvotes: 3
Reputation: 951
In a React app with StrictMode:
And if you know that StrictMode helps you optimize your app in some way
And you don't want to disable StrictMode entirely
Then:
The React Developer Tools Chrome Extension offers an option to Hide logs during second render in Strict Mode. To enable that:
You will no more see the dual logs in the console.
Upvotes: 18
Reputation: 976
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,
}
Upvotes: 41
Reputation: 573
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
Upvotes: 45
Reputation: 1040
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
Upvotes: 0
Reputation: 8907
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')
);
Upvotes: 756