DEV Community

Pritam Shrestha
Pritam Shrestha

Posted on

3 3

React Strict Mode - Good Parts Only

StrictMode is a tool for highlighting potential problems in an application. Like FragmentStrictMode does not render any visible UI. It activates additional checks and warnings for its descendants.

Example:

import React from 'react';

function ExampleApplication() {
  return (
    <div>
      <Header />
      <React.StrictMode>
        <div>
          <ComponentOne />
          <ComponentTwo />
        </div>
      </React.StrictMode>
      <Footer />
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

In the above example, strict mode checks will not be run against the Header and Footer components. However, ComponentOne and ComponentTwo, as well as all of their descendants, will have the checks.

💡 Note:
Strict mode checks are run in development mode only; they do not impact the production build.

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 constructorrender, and shouldComponentUpdate methods
  • Class component static getDerivedStateFromProps method
  • Function component bodies
  • State updater functions (the first argument to setState)
  • Functions passed to useStateuseMemo, or useReducer

By intentionally double-invoking methods like the component constructor, strict mode makes patterns like this easier to spot.

💡 The double invocation is the reason why we see double logs in the console when we do not expect them at all.

💡 Note:

Starting with React 17, React automatically modifies the console methods like console.log() to silence the logs in the second call to lifecycle functions. (Not the function bodies) However, it may cause undesired behavior in certain cases where a workaround can be used.

References

Strict Mode - React

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more