Explain Codes LogoExplain Codes Logo

My React Component is Rendering Twice Because of Strict Mode

javascript
react
strict-mode
development-tool
Nikita BarsukovbyNikita Barsukov·Mar 1, 2025
TLDR

The double rendering you're witnessing is due to React's Strict Mode. Specifically, it's a tool designed for uncovering problems during development by rendering your components twice. To prevent this double render, you can remove <React.StrictMode> from your index.js:

// Now the bartender only serves my component one beer 🍺 ReactDOM.render(<App />, document.getElementById('root'));

Remember though, this is only a dev mode phenomenon; in production, React serves responsibly, once per call.

Grasping the scope of Strict Mode

Strict Mode is more than double trouble. It's a development tool that helps catch potential problems in your application. By double rendering components, it makes unexpected side effects stand out.

The intersection of Strict Mode and your needs

Before removing <React.StrictMode>, rethink:

  • Are you fully aware of your components' side effects?
  • Are you confident no dev oversights happened during the app build phase?

If you're unsure, despite the double renders, Strict Mode should stay as your code quality cop.

It's not a Strict-Mode-or-Bust situation

Despite the potential benefits of Strict Mode, there are circumstances you might choose to remove it:

  • You completely comprehend the downside.
  • You maintain a stable code base with no active new development.
  • Your team is satisfied with the app's current state and performance.

When double rendering might bug you

Strict Mode's double rendering is confined to development, but can still throw curveballs your way.

Impact on performance

Strict Mode's double check might slow down your app and retrigger hefty calculations.

False alarms

Double renders can mislead developers about the sequence of hooks or lifecycle events.

Testing woes

Your tests might need tweaking to account for the double rendering and avoid inaccurate results.

Strategies to adapt to Strict Mode and its quirks

You've now weighed in the pros and cons of the Strict Mode. Let's fine-tune your dev environment based on that decision.

Unleashing React Developer Tools

Use the React Developer Tools extension to trim down the noise. Enable "Hide logs during second render in Strict Mode" to declutter your console.

Disabling Strict Mode in Next.js

For Next.js applications, set reactStrictMode: false in next.config.js to give Strict Mode a day off.

Partial application of Strict Mode

Wrap only the risky or complex components in <React.StrictMode> for localized application of Strict Mode.