Software

React Strict Mode: What It Does and Why It Matters

When learning React, you may have noticed a component called <React.StrictMode> or <StrictMode> wrapped around your application. At first, it can be confusing.…

D
DevByteTechnical Author
Published
14 min read4 views
React Strict Mode: What It Does and Why It Matters

When developing a React application, you may notice something confusing: a component renders twice, a useEffect() hook runs more than once, or a message appears twice in the browser console.

If you have encountered this behavior, React Strict Mode might be the reason.

React Strict Mode is a built-in feature that helps developers identify potential problems in their applications during development. It performs additional checks to reveal issues such as impure rendering, missing effect cleanup, and incorrect ref handling before those issues become harder to detect.

However, many beginners misunderstand Strict Mode. Some developers assume it is a performance optimization, while others disable it because they think it causes unnecessary rendering.

Understanding how Strict Mode works can help you write more predictable, maintainable, and reliable React applications.

In this guide, we will explain what React Strict Mode is, how it works, why components sometimes render twice, how it affects useEffect(), and how to handle the issues it reveals.

What Is React Strict Mode?

React Strict Mode is a development tool that helps identify common bugs and potential problems in React applications.

It is implemented using the built-in StrictMode component, which you can import from React.

Unlike a regular HTML element, Strict Mode does not render any visible UI. Instead, it enables additional development-time checks for the components inside its boundary.

Here is a basic example:

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App";

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

In this example, the App component and its descendants are checked by Strict Mode.

These checks help developers identify problems before releasing an application to production.

According to the official React documentation, Strict Mode can help detect:

  • Impure rendering logic

  • Missing cleanup functions in effects

  • Missing cleanup in callback refs

  • Usage of deprecated APIs

An important point is that Strict Mode does not affect the production build in the same way it affects development. Its additional checks are development-only.

Official documentation: https://react.dev/reference/react/StrictMode

Why Does React Strict Mode Render Components Twice?

One of the most common questions developers ask is:

Why does my React component render twice even though I called it only once?

Consider this example:

function App() {
  console.log("App component rendered");

  return (
    <div>
      <h1>Hello, React!</h1>
    </div>
  );
}

export default App;

If you render this component inside Strict Mode, you may see the following output during development:

App component rendered
App component rendered

This behavior is intentional.

React calls certain functions an additional time in development to help reveal unexpected side effects and impure logic.

A React component should ideally behave like a pure function: given the same props, state, and context, it should produce the same UI without modifying external data during rendering.

For example, consider this incorrect component:

function ProductList({ products }) {
  products.push({
    id: 100,
    name: "New Product",
  });

  return (
    <ul>
      {products.map((product) => (
        <li key={product.id}>
          {product.name}
        </li>
      ))}
    </ul>
  );
}

The problem is that the component modifies the original products array received through props.

If React renders the component more than once, the product may be added repeatedly.

This can lead to unpredictable behavior.

How to Fix It

Instead of modifying the original array, create a new array:

function ProductList({ products }) {
  const updatedProducts = [
    ...products,
    {
      id: 100,
      name: "New Product",
    },
  ];

  return (
    <ul>
      {updatedProducts.map((product) => (
        <li key={product.id}>
          {product.name}
        </li>
      ))}
    </ul>
  );
}

Now the original array remains unchanged.

However, if adding a product is supposed to be a user action, it is generally better to update state through an event handler rather than constructing a new product list during rendering.

The important lesson is that rendering should calculate the UI, not perform unrelated side effects.

Strict Mode helps expose these problems by making certain functions run an extra time during development.

Does React Strict Mode Run in Production?

No. Strict Mode's additional development checks do not run in production builds.

For example, consider:

import { StrictMode } from "react";

function App() {
  console.log("Rendering App");

  return <h1>Hello World</h1>;
}

export default function Root() {
  return (
    <StrictMode>
      <App />
    </StrictMode>
  );
}

During development, you may see the component's render logic executed twice when React performs its Strict Mode checks.

In production, these additional Strict Mode checks are disabled.

This distinction is important because developers sometimes assume that the double rendering they observe locally will automatically affect production performance.

That is not how Strict Mode works.

However, you should still investigate expensive rendering logic or unnecessary state updates. Those issues can affect performance independently of Strict Mode.

How Does React Strict Mode Affect useEffect()?

Another common source of confusion is the useEffect() hook.

Consider the following component:

import { useEffect } from "react";

function App() {
  useEffect(() => {
    console.log("Effect executed");
  }, []);

  return <h1>Hello World</h1>;
}

export default App;

In development, when the component is initially mounted under root-level Strict Mode, React performs an additional effect setup-and-cleanup cycle.

Because this effect has no cleanup function, the console may display:

Effect executed
Effect executed

This behavior helps React detect effects that do not correctly clean up their resources.

It is important to understand that Strict Mode is not simply executing every effect twice under every circumstance. The additional behavior applies to specific development checks, particularly the initial mounting behavior when Strict Mode is enabled at the root.

Why Is This Important?

Effects are often used to interact with systems outside React, including:

  • Browser event listeners

  • WebSocket connections

  • Timers

  • External subscriptions

  • Third-party libraries

  • Network requests

These resources may need cleanup when an effect is no longer active.

If an effect creates a resource but never releases it, your application may develop memory leaks, duplicate subscriptions, or other unexpected behavior.

Strict Mode makes these problems easier to identify.

Official reference: https://react.dev/reference/react/useEffect

How to Fix Missing Cleanup in useEffect()

Consider a component that subscribes to an external event:

import { useEffect } from "react";

function App() {
  useEffect(() => {
    window.addEventListener("resize", () => {
      console.log("Window resized");
    });
  }, []);

  return <h1>Resize the browser window</h1>;
}

export default App;

The code adds an event listener but does not remove it.

This is a problem because the listener can remain active after the effect is no longer needed.

A better implementation defines the callback separately and removes the listener during cleanup:

import { useEffect } from "react";

function App() {
  useEffect(() => {
    const handleResize = () => {
      console.log("Window resized");
    };

    window.addEventListener("resize", handleResize);

    return () => {
      window.removeEventListener("resize", handleResize);
    };
  }, []);

  return <h1>Resize the browser window</h1>;
}

export default App;

The cleanup function is returned from the effect.

React calls it when the effect needs to be cleaned up, including during Strict Mode's additional development checks.

The sequence on initial mounting under root-level Strict Mode is effectively:

  1. Set up the effect.

  2. Clean up the effect.

  3. Set up the effect again.

This helps verify that the effect can be started and stopped correctly.

Best practice: Whenever an effect creates a subscription, event listener, timer, or external connection, consider how that resource should be cleaned up.

Does Strict Mode Cause Duplicate API Calls?

Yes, you may observe duplicate API requests during development when a request is initiated inside an effect that runs during Strict Mode's additional checks.

For example:

import { useEffect } from "react";

function Users() {
  useEffect(() => {
    fetch("/api/users")
      .then((response) => response.json())
      .then((data) => {
        console.log(data);
      });
  }, []);

  return <h1>Users</h1>;
}

export default Users;

Under root-level Strict Mode, this effect may initiate two requests during the initial development mounting checks.

This can be confusing when inspecting the browser's Network tab.

However, simply removing Strict Mode is not the best solution.

Instead, determine whether the request should be managed by an effect, a data-fetching library, a framework's data-loading mechanism, or a user event handler.

Example: Cancelling an Outdated Request

You can use AbortController to cancel a request when its effect is cleaned up:

import { useEffect, useState } from "react";

function Users() {
  const [users, setUsers] = useState([]);
  const [error, setError] = useState("");

  useEffect(() => {
    const controller = new AbortController();

    async function fetchUsers() {
      try {
        const response = await fetch("/api/users", {
          signal: controller.signal,
        });

        if (!response.ok) {
          throw new Error("Failed to fetch users");
        }

        const data = await response.json();
        setUsers(data);
      } catch (error) {
        if (error.name !== "AbortError") {
          setError(error.message);
        }
      }
    }

    fetchUsers();

    return () => {
      controller.abort();
    };
  }, []);

  if (error) {
    return <p>{error}</p>;
  }

  return (
    <ul>
      {users.map((user) => (
        <li key={user.id}>
          {user.name}
        </li>
      ))}
    </ul>
  );
}

export default Users;

When React cleans up the effect, the associated request can be aborted.

This helps prevent an outdated request from continuing unnecessarily.

There is one important limitation: cancelling a browser request does not guarantee that a server has not already received or processed it.

For operations that change server data, such as creating a payment or placing an order, avoid initiating the operation merely because a component mounted. Trigger such operations through the appropriate user action and design the backend to handle retries safely.

For data fetching, a library with caching and request deduplication may be more appropriate for a larger application.

How to Enable React Strict Mode

Enabling Strict Mode is straightforward.

Method 1: Enable Strict Mode for the Entire Application

In a standard React application using createRoot(), wrap your root component with StrictMode.

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App";

const root = createRoot(
  document.getElementById("root")
);

root.render(
  <StrictMode>
    <App />
  </StrictMode>
);

This enables Strict Mode checks throughout the component tree.

For new React applications, enabling Strict Mode is generally recommended.

Method 2: Enable Strict Mode for a Specific Section

You can also wrap only part of the application:

import { StrictMode } from "react";

function App() {
  return (
    <>
      <header>
        <h1>My Application</h1>
      </header>

      <StrictMode>
        <main>
          <Dashboard />
          <UserProfile />
        </main>
      </StrictMode>

      <footer>
        <p>Copyright 2027</p>
      </footer>
    </>
  );
}

In this example, Strict Mode checks apply to the components inside the StrictMode boundary and their descendants.

This can be useful when incrementally introducing Strict Mode into an older application.

Keep in mind that when Strict Mode is enabled only for a nested part of the tree, React does not perform every root-level initial-mount check that would create a behavior impossible in production.

How to Use React Strict Mode in Next.js

Strict Mode is also relevant to developers building applications with Next.js.

In modern Next.js applications using the App Router, Strict Mode has been enabled by default since Next.js 13.5.1.

For applications using the Pages Router, the reactStrictMode setting in next.config.js can be used to configure it.

For example:

module.exports = {
  reactStrictMode: true,
};

The exact configuration depends on your Next.js version and project setup.

If your components render more than once during development, check whether Strict Mode is enabled before assuming there is a bug in Next.js itself.

You should also inspect your component logic, effects, and state updates to determine why the additional checks are exposing unexpected behavior.

Official reference: https://nextjs.org/docs/app/api-reference/config/next-config-js/reactStrictMode

Should You Disable React Strict Mode?

In most cases, you should keep Strict Mode enabled.

Disabling it may make duplicate logs or repeated effect setup disappear, but it does not necessarily fix the underlying problem.

For example, if an effect leaks event listeners, disabling Strict Mode might hide the issue during initial development. The leak can still occur when the component is mounted and unmounted through normal application interactions.

Before considering disabling Strict Mode, ask yourself:

  • Does the component modify props or external data during rendering?

  • Does the effect clean up its resources correctly?

  • Are event listeners and subscriptions removed?

  • Does the application depend on an effect running only once?

  • Is a third-party library compatible with the expected setup and cleanup behavior?

  • Can the repeated operation be moved into an appropriate event handler or managed by a data-fetching library?

Fixing the underlying issue is usually more valuable than suppressing the development check.

If an older application has compatibility problems, you can introduce Strict Mode incrementally and investigate the affected components.

Common Mistakes Developers Make With Strict Mode

1. Assuming Double Rendering Is a Production Bug

Seeing a component render twice in development does not automatically mean the application is broken.

Strict Mode intentionally repeats certain operations to identify problems.

Investigate whether the rendering logic is pure and whether the extra checks reveal a genuine issue.

2. Removing Strict Mode to Hide Duplicate API Calls

Removing Strict Mode can hide the symptom without addressing the reason an effect performs an operation.

Review the data-fetching approach, request cancellation, caching, and effect cleanup before changing the application configuration.

3. Using a Ref to Prevent the Second Effect Execution

Some developers attempt to bypass the additional effect execution by using a ref:

const hasRun = useRef(false);

useEffect(() => {
  if (hasRun.current) {
    return;
  }

  hasRun.current = true;

  // Perform some operation
}, []);

This approach can hide missing cleanup logic rather than solving it.

If an effect creates a connection or subscription, the component still needs a reliable way to release that resource.

Write effects so they can be set up and cleaned up correctly instead of relying on them to execute only once.

4. Performing Side Effects During Rendering

Avoid making API requests, modifying global variables, or directly changing props inside a component's render logic.

Rendering should calculate the UI from the current inputs.

Place side effects in the appropriate effect, event handler, or data-loading mechanism.

5. Ignoring Third-Party Library Warnings

Older libraries may rely on deprecated React APIs or assume particular component lifecycle behavior.

Strict Mode can expose these compatibility issues.

Check for updated versions of the library and consult its documentation before adding workarounds.

React Strict Mode Best Practices

To use Strict Mode effectively, follow these practices:

  1. Keep components pure: Avoid modifying existing objects, arrays, or external variables during rendering.

  2. Clean up effects: Remove event listeners, cancel timers, and release subscriptions when appropriate.

  3. Handle asynchronous operations carefully: Prevent outdated requests from updating state unnecessarily.

  4. Avoid mount-triggered mutations: Do not perform payments, create orders, or execute other important server-side mutations simply because a component mounted.

  5. Use stable keys: Provide appropriate keys when rendering lists so React can identify elements correctly.

  6. Test component lifecycle behavior: Check that components behave correctly when mounted, cleaned up, and mounted again.

  7. Use modern React APIs: Replace deprecated patterns where possible.

  8. Keep Strict Mode enabled: Let development checks help identify issues early.

  9. Investigate performance separately: Extra development checks do not mean every production render is duplicated.

  10. Use appropriate data-fetching tools: For larger applications, consider framework-level data loading or a suitable library with caching and request management.

These practices make your components more predictable and help prevent problems that may otherwise appear only after users interact with the application.

Frequently Asked Questions

What is React Strict Mode used for?

React Strict Mode helps detect potential bugs in React applications during development. It checks for issues such as impure rendering, missing effect cleanup, incorrect callback ref handling, and deprecated APIs.

Why does React Strict Mode render twice?

Strict Mode intentionally calls certain functions an additional time during development to expose unexpected side effects and impure rendering logic. This extra check does not mean that every component always renders twice.

Does Strict Mode affect production performance?

Strict Mode's additional checks are development-only and do not affect production builds in the same way. Production performance issues should still be investigated independently.

Why does useEffect run twice in React Strict Mode?

When Strict Mode is enabled at the root, React performs an additional setup-and-cleanup cycle for effects during initial mounting in development. This helps identify missing cleanup logic and effects that cannot safely be restarted.

Should I remove Strict Mode if my API is called twice?

Generally, no. First inspect the effect, request cancellation, caching, and data-fetching strategy. Removing Strict Mode may hide the development symptom without fixing the underlying issue.

Is React Strict Mode enabled by default in Next.js?

In the Next.js App Router, Strict Mode has been enabled by default since Next.js 13.5.1. Pages Router projects can configure it through reactStrictMode in next.config.js.

Is React Strict Mode the same as JavaScript strict mode?

No. JavaScript strict mode changes certain language behaviors and catches some programming errors. React Strict Mode is a React development feature that performs additional checks on components and related behavior.

Conclusion

React Strict Mode is an important development tool that helps you identify bugs before they reach production.

Its additional checks can reveal impure rendering, missing effect cleanup, incorrect callback ref handling, and deprecated API usage. The repeated rendering or effect execution you observe during development is intentional and should be understood rather than automatically disabled.

When working with Strict Mode, focus on writing pure components, cleaning up effects correctly, handling asynchronous requests safely, and avoiding side effects during rendering.

If your application behaves unexpectedly under Strict Mode, investigate the underlying cause instead of immediately removing the wrapper.

The key takeaway is simple: React Strict Mode helps you build components that behave correctly when React renders them more than once and when effects need to be started, stopped, and started again.

D
DevByteAuthor

Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.

Keep Exploring

Related Engineering Dispatches

More guides and architectural patterns you might find valuable.

Browse All Articles↘