DEV Community

Cover image for What is Strict Mode in React?
Code of Relevancy
Code of Relevancy

Posted on • Edited on

What is Strict Mode in React?

Hello React developers, you've probably heard of strict mode. But what the hell is it, exactly? In short term, React.StrictMode is a useful component for highlighting potential problems in an application. Just like <Fragment>, <StrictMode> does not render any extra DOM elements.. With this article, we'll dive into the details of what strict mode is, how it works and why you should consider using it in your applications..


What is Strict Mode in React?

Strict mode is a set of development tools that help you catch potential problems in your code before they become actual bugs. When you enable strict mode in your React application, you're essentially telling React to turn on a bunch of extra checksπŸ‘€ and warnings that are designed to help you write better code. These checks and warnings can catch things like:

  1. Components with side effects
  2. Deprecated or unsafe lifecycle methods
  3. Unsafe use of certain built in functions
  4. Duplicate keys in lists

StrictMode


Enabling Strict Mode

Enabling strict mode in your React application is actually very easy. You can do it by adding a single line of code to your main index.js file. Let's see:

import React from 'react';
import ReactDOM from 'react-dom';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);
Enter fullscreen mode Exit fullscreen mode

Enabling strict mode for a part of the app

You can also enable Strict Mode for any part of your application:

import { StrictMode } from 'react';

function App() {
  return (
    <>
      <Header />
      <StrictMode>
        <main>
          <Sidebar />
          <Content />
        </main>
      </StrictMode>
      <Footer />
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

In this instance, Strict Mode checks will not run against the Header and Footer components. But, they will run on Sidebar and Content, as well as all of the components inside them, no matter how deep it is..


Strict mode affects only the development environment

It's important to note that strict mode has no effect on the production build of your React application. This means that any checks or warnings that are enabled by strict mode will not be present in the final version of your application that users see. As we have seen, strict mode turns on extra checks and warnings, it can potentially slow down your development environment..

Strict mode affects only the development environment


Strict mode can help you catch subtle bugs

Sometimes bugs in React applications can be difficult to track down, especially if they're caused by subtle issues like race conditions or incorrect assumptions about component state. By enabling strict mode and taking advantage of the extra checks and warnings it provides, you may be able to catch these bugs before they cause serious problems..


Strict mode can help you stay up-to-date with best practices

React is a rapidly evolving framework and best practices can change over time. By enabling strict mode and paying attention to the warnings and suggestions it provides, you can ensure that your React code is up-to-date and following current best practices. Such as using the key prop when rendering lists or avoiding side effects in render()..


Highlighting potential problems early

Strict mode can catch issues in your code that may cause problems in coming future, before they become serious problems. Let's say, it can detect and warn about deprecated lifecycle methods as well as access to findDOMNode() which is no longer recommended..

findDOMNode

findDOMNode


Preventing common mistakes

By enabling strict mode, you can avoid common mistakes that may not be immediately obvious, such as modifying the state directly instead of using setState() or using undeclared variables.


Identifying Unsafe Lifecycles

React Strict Mode can help identify the use of unsafe lifecycle methods in your components. For instance, it can warn you about the use of the componentWillUpdate and componentWillReceiveProps methods which are both considered unsafe and will be removed in future versions of React..

Unsafe Lifecycles

Let's say you have a component that uses componentWillReceiveProps() to update its state based on incoming props:

class BlackMamba extends React.Component {
  constructor(props) {
    super(props);
    this.state = { venom: props.venom };
  }

  componentWillReceiveProps(nextProps) {
    this.setState({ venom: nextProps.venom });
  }

  render() {
    return <div>{this.state.venom}</div>;
  }
}
Enter fullscreen mode Exit fullscreen mode

With regular mode, this component would work as expected, but in React.StrictMode, you would see a warning in the console:

Warning: BlackMamba uses componentWillReceiveProps, which is considered an unsafe lifecycle method. Instead, use static getDerivedStateFromProps.


Warning About Legacy String ref API Usage

Strict Mode can also warn you about the use of the legacy string ref API, which is considered deprecated. But, you should use the createRef API, which is safer and easier to use..

Legacy String ref API Usage

Let's say, you have a component that uses a string ref like this:

import { Component } from "react";
import { createRoot } from "react-dom/client";

class BlackMamba extends Component {
  componentDidMount() {
    this.refs.venom.focus();
  }

  render() {
    return (
      <>
        <h1>Black Mamba</h1>
        <input ref="venom" />
      </>
    );
  }
}

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

root.render(<BlackMamba />);
Enter fullscreen mode Exit fullscreen mode

Legacy string ref API is considered deprecated, still you'll not see any errors in console.

Output

When you enable React.StrictMode in your app like this:

import { StrictMode, Component } from "react";
import { createRoot } from "react-dom/client";

class BlackMamba extends Component {
  componentDidMount() {
    this.refs.venom.focus();
  }

  render() {
    return (
      <>
        <h1>Black Mamba</h1>
        <input ref="venom" />
      </>
    );
  }
}

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

root.render(
  <StrictMode>
    <BlackMamba />
  </StrictMode>
);
Enter fullscreen mode Exit fullscreen mode

You'll see a warning in the console that looks like this:

Warning: A string ref, "venom", has been found within a strict mode tree. String refs are a source of potential bugs and should be avoided. We recommend using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref

Output

Let's fix it with createRef API:

import { StrictMode, Component, createRef } from "react";
import { createRoot } from "react-dom/client";

class BlackMamba extends Component {
  constructor(props) {
    super(props);

    this.venom = createRef();
  }

  componentDidMount() {
    this.venom.current.focus();
  }

  render() {
    return (
      <>
        <h1>Black Mamba</h1>
        <input ref={this.venom} />
      </>
    );
  }
}

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

root.render(
  <StrictMode>
    <BlackMamba />
  </StrictMode>
);
Enter fullscreen mode Exit fullscreen mode

Bravo, it's fixed :)

Output


Detecting Legacy Context API

The legacy Context API is deprecated in React and has been replaced with the new Context API. React Strict Mode can help you detect any usage of the legacy Context API and encourage you to switch to the new API

Detecting Legacy Context API


If you're not already using strict mode, it's definitely worth considering!!!


❀ Motivation:

Motivation


πŸ€Support

Please consider following and supporting us by subscribing to our channel. Your support is greatly appreciated and will help us continue creating content for you to enjoy. Thank you in advance for your support!

YouTube
Discord
GitHub

Dour Darcel #8740

Top comments (29)

Collapse
 
sergeyleschev profile image
Sergey Leschev

Great article on Strict Mode in React! As a developer, I appreciate any tool or component that helps me catch potential problems before they cause issues for users. It's great to see how can highlight issues and improve the overall quality of an application. In our projects, we also use strict mode in our React applications to ensure best practices are followed and the performance is optimized. Thanks for sharing this informative piece!

Collapse
 
codeofrelevancy profile image
Code of Relevancy

Glad you found it helpful.. Thank you for your great feedback. Happy coding..

Collapse
 
dmikester1 profile image
Mike Dodge

Very helpful and informative article! I never understood what strict mode was for. I just wish there was a way to make it work with WebSockets. I've had to disable Strict Mode to get WebSockets to work. github.com/facebook/create-react-a...

Collapse
 
duxtech profile image
Cristian Fernando

good article!

Collapse
 
codeofrelevancy profile image
Code of Relevancy

Thank you my friend

Collapse
 
fruntend profile image
fruntend

Π‘ongratulations πŸ₯³! Your article hit the top posts for the week - dev.to/fruntend/top-10-posts-for-f...
Keep it up πŸ‘

Collapse
 
codeofrelevancy profile image
Code of Relevancy

Thanks a ton man..

Collapse
 
sherrydays profile image
Sherry Day

Thanks for this.

Can you provide examples of how React.StrictMode helps identify issues related to unsafe lifecycle methods or improper use of the ref API in a developer's code?

Collapse
 
codeofrelevancy profile image
Code of Relevancy

I have updated the article as per your request..

Collapse
 
codeofrelevancy profile image
Code of Relevancy

Thanks for reading it.
You have a good point, I will update the article accordingly..

Collapse
 
abhixsh profile image
Abishek Haththakage

great article

Collapse
 
codeofrelevancy profile image
Code of Relevancy

Thank you bro

Collapse
 
yogini16 profile image
yogini16

Wow, great article.
Thank you for this post

Collapse
 
codeofrelevancy profile image
Code of Relevancy

Thank you..

Collapse
 
roix profile image
roix

Any reason this not enabled by default?

Collapse
 
codeofrelevancy profile image
Code of Relevancy

Hmm, it may have a negative impact on the performance of your app if it's enabled as default. performs some additional checks to catch the potential bugs..

Collapse
 
bybydev profile image
byby.dev

This is a great article! You did a great job explaining Strict Mode in React. I learned a lot from it. Thanks for sharing!

Collapse
 
codeofrelevancy profile image
Code of Relevancy

Thank you for sharing kind words

Collapse
 
codebucks profile image
CodeBucks

Great article and explanation.

Collapse
 
codeofrelevancy profile image
Code of Relevancy

Thank you boss πŸ™