React StrictMode

By

Published · Updated

Tagged: React

Learn how React StrictMode finds impure rendering, missing Effect cleanup, ref cleanup bugs, and deprecated APIs during development.

StrictMode helps you find common React bugs during development.

Wrap the root component to enable it for the whole application:

import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import App from './App.jsx'

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <App />
  </StrictMode>
)

You may already have it. The React template of Vite (npm create vite@latest) puts this exact wrapper in src/main.jsx. That’s why many people meet Strict Mode for the first time when they see their component render twice.

What Strict Mode does

Strict Mode enables additional development-only behavior:

This can make a component appear to render twice while you are developing. React is checking whether your rendering logic and cleanup code are safe to run again.

Do not remove Strict Mode to hide those problems. Fix the component that causes them.

Why my component renders twice

React calls these functions twice in development:

These functions should be pure: same input, same output, no side effects. If they are, running them twice changes nothing. If one of them changes something outside, the second call makes the bug visible.

Here is a classic one. This component mutates an array it doesn’t own while rendering:

const items = []

function List() {
  items.push('new item') // side effect during render
  return <p>{items.length} items</p>
}

With Strict Mode you see 2 items right away instead of 1, and you know something is wrong. Without it, the bug would show up later, at some random re-render.

The fix is to keep render pure, for example by building a new array instead of changing a shared one.

If you have React DevTools installed, the console.log calls from the second render appear dimmed in the console. DevTools also has a setting to hide them completely.

Why my useEffect runs twice

In development, Strict Mode runs one extra setup and cleanup cycle for every Effect when the component mounts. So you see setup, cleanup, setup.

This finds Effects that don’t clean up after themselves. The fix is to return a cleanup function that undoes what the setup did:

useEffect(() => {
  const connection = createConnection()
  connection.connect()
  return () => connection.disconnect()
}, [])

The same goes for event listeners:

useEffect(() => {
  window.addEventListener('scroll', handleScroll)
  return () => window.removeEventListener('scroll', handleScroll)
}, [])

With a cleanup, connecting, disconnecting and connecting again leaves you with one connection, like in production.

For data fetching, you’ll see 2 requests in the Network tab. Use a flag so the first, outdated response doesn’t overwrite the state:

useEffect(() => {
  let ignore = false

  async function startFetching() {
    const json = await fetchTodos(userId)
    if (!ignore) {
      setTodos(json)
    }
  }

  startFetching()

  return () => {
    ignore = true
  }
}, [userId])

This also fixes a real production bug: when userId changes quickly, a slow old response can’t replace the newer one.

Don’t use a ref to stop the Effect from running the second time. The React docs say this hides the message but doesn’t fix the bug. I wrote more about this in why does useEffect run two times?.

Enable it for part of the app

You can also enable it for one part of the application:

function App() {
  return (
    <>
      <Header />
      <StrictMode>
        <Checkout />
      </StrictMode>
    </>
  )
}

This is handy when you add Strict Mode to an old app. Turn it on for one section, fix the warnings, then move it up the tree.

There’s no way to turn it off for a component inside a tree that is wrapped in <StrictMode>.

Deprecated APIs

Strict Mode also warns you when you use APIs that React plans to remove, like the UNSAFE_ class lifecycle methods (UNSAFE_componentWillMount and friends). Check the console for these warnings.

Production

Strict Mode does not add the extra checks to the production build.

So you don’t need to remove it before you deploy. Components render once and Effects run once in production, even with the <StrictMode> wrapper in your code.

Want me to talk about your product? You can sponsor this site.

Related posts about react: