Strict Mode

Priyanka Patwal
Last Updated: May 13, 2022

Introduction

Strict mode is a React assistance feature that allows us to develop more efficient React code. If we don't follow the React guidelines, it warns us, but it only functions in development mode.

 

Strict mode is a React Developer Tool primarily used to highlight potential issues in a web app. For its descendant components, it activates additional depreciation checks and warnings. 

 

The fact that it gives visible feedback (warning/error messages) whenever the React rules and suggested practices are not followed is one of the reasons for its popularity. The React StrictMode Component, like the React Fragment, does not render any visible UI.

 

Example:

<comp1>

   <React.StrictMode>

      <comp2/>

   <React.StrictMode/>

<comp2>

 

 

 

Use Cases of Strict Mode

Following are some of the use cases of strict mode.

1. Identifying components with unsafe lifecycles

In async React apps, some legacy lifecycle methods are dangerous to employ. It can be tough to ensure that these life cycles aren't used if your application employs third-party libraries. Thankfully, Strict mode can assist us with this!

 

The following are some examples of legacy component life cycles that encourage dangerous coding practices:

  1. componentWillMount
  2. componentWillReceiveProps
  3. componentWillUpdate

 

When strict mode is activated, React compiles a list of all class components that have unsafe lifecycles and console logs a warning message with details, such as:

2. Warning about legacy string ref API usage

 

The old string ref API and the callback API were previously the only ways to manage refs in React. Although the string ref API was handier, it had several drawbacks. Therefore the official recommendation was to use the callback form instead.

 

React 16.3 added a third approach that has all of the benefits of a string ref but none of the drawbacks:

class MyComponent extends React.Component {

  constructor(props) {

    super(props);

    this.inputRef = React.createRef();

 }

 

  render() {

    return <input type="text" ref={this.inputRef} />;

 }

componentDidMount() {

  this.inputRef.current.focus();

 }

}

 

 

Since string refs were replaced mainly by object refs, strict mode now warns against using string refs.

3. Warning about deprecated findDOMNode usage

 

FindDOMNode was a feature in React that allowed you to search the tree for a DOM node given a class instance. You usually don't need this because you can link a ref to a DOM node directly.

 

Although findDOMNode may be used on class components, this was breaking abstraction levels by allowing a parent to specify which children should be rendered. It introduces a refactoring danger by preventing you from changing a component's implementation details since a parent may reach its DOM node. 

 

Although findDOMNode only returns the single child, using Fragments allows a component to render multiple DOM nodes. findDOMNode is a read-only API. You only got a response when you asked for it. 

 

There is no way to manage this change if a child component renders a different node. As a result, findDOMNode only worked if components always returned the same DOM node.

 

You may make this clear by supplying a ref to your custom component and utilizing ref forwarding to pass it to the DOM.

You can also create a wrapper DOM node and attach a ref to it directly in your component.

class MyComponent extends React.Component {

  constructor(props) {

    super(props);

    this.wrapper = React.createRef();

 }

  render() {

    return <div ref={this.wrapper}>{this.props.children}</div>;

 }

}

 

4. Detecting unexpected side effects

React works in two phases conceptually:

  • The render phase determines what changes, such as to the DOM, are required. React calls render during this phase and then compares the result to the previous render.
  • React applies any modifications during the commit process. (This is when React inserts, changes, and removes DOM nodes in React DOM.) During this phase, React also calls lifecycles like componentDidMount and componentDidUpdate.

Although the commit phase usually is quick, rendering can be slow. To prevent stopping the browser, the future concurrent mode (which is not activated by default yet) divides the rendering effort into portions, pausing and resuming the process. This means that React can call render phase lifecycles multiple times before committing, or it can call them without committing (because of an error or a higher priority interruption).

The following class component methods are included in render phase lifecycles:

  1. constructor
  2. componentWillMount (or UNSAFE_componentWillMount)
  3. componentWillReceiveProps (or UNSAFE_componentWillReceiveProps)
  4. componentWillUpdate (or UNSAFE_componentWillUpdate)
  5. getDerivedStateFromProps
  6. shouldComponentUpdate
  7. render
  8. setState updater functions (the first argument)

Because the procedures listed above may be used multiple times, they mustn't have any adverse effects. Ignoring this rule might result in memory leaks and invalid application states, among other issues. Unfortunately, because these issues are frequently non-deterministic, detecting them can be challenging.

The strict mode won't automatically detect side effects for you, but it will make them more deterministic, which will help you spot them. This is accomplished by double calling the following routines:

 

  • Class component constructor, render, and shouldComponentUpdate methods
  • Class component static getDerivedStateFromProps method
  • Function component bodies
  • State updater functions (the first argument to setState)
  • Functions passed to useState, useMemo, or useReducer

5. Detecting legacy context API

The legacy context API is prone to errors, and it will be phased out in a future major release. It still works for all 16.x releases, but in strict mode, it will display the following warning message:

Frequently asked questions

 

1). What does a strict mode do in React?

Strict mode is a React assistance feature that allows us to develop more efficient React code. If we don't follow the React guidelines, it warns us, but it only functions in development mode.

 

2). When should we use Strict mode?

ReactStrictMode is a built-in component used to enable a series of tests that React executes and notifies you about.

 

3). Why does React strict mode render twice?

StrictMode renders components twice (on dev but not in production) to detect and tell you about any issues with your code (which can be pretty helpful).

Key Takeaways

 

Strict mode is a React assistance feature that allows us to develop more efficient React code. If we don't follow the React guidelines, it warns us, but it only functions in development mode.

Use cases of Strict Mode are:

1. Identifying components with unsafe lifecycles

2. Warning about legacy string ref API usage:

3. Warning about deprecated findDOMNode usage

4. Detecting unexpected side effects

 

Happy Learning!

 

Was this article helpful ?
0 upvotes

Comments

No comments yet

Be the first to share what you think