React strict mode - React.StrictMode

Strict mode (realtc. Strictmode)

StrictMode is a tool to mark potential problems in applications. It's Fragment. StrictMode doesn't render any real UI. It triggers an additional check warning for its descendant elements

Note: strict mode check only operates in development mode and will not conflict with production mode

Strict mode can be enabled anywhere in the code. For example:

// Entry file
React.render(
    <React.StrictMode>
        <App />
    </React.StrictMode>,
    document.getElementById("root")
)
// In a single component
import React from "react";
function Home(){
    return (
        <div className="home">
            <React.StrictMode>
                <ComponentTable />
                <ComponentDialog />
            </React.StrictMode>
            <CommonInfo />
        </div>
    ) 
}

In the above case, when used in the entry file, all its descendant elements will be checked; When used in a single component, the commenttable and CommonDialog and all their descendant elements will be checked, and the strict mode will not be run on the CommonInfo component

Advantages of using StrictMode:

  • Identify unsafe claim cycle components
  • Warning about legacy string ref usage
  • Warning about using the obsolete findDOMMode method
  • Detect unexpected side effects
  • Obsolete context API detected

Lifecycle warning

Outdated component life cycle often leads to unsafe coding practices. The specific functions are as follows:

  1. componentWillMount
  2. componentWillReceiveProps
  3. componentWillUpdate

16.3: introducing aliases for unsafe life cycles

  1. UNSAFE_componentWillMount
  2. UNSAFE_componentWillReceiveProps
  3. UNSAFE_componentWillUpdate
1,componentWillMount (Old name (normal use)
2,componentWillReceiveProps(Old name (normal use)
3,componentWillUpdate(Old name (normal use)

16.3<16.x<17.0

  1. UNSAFE_componentWillMount
  2. UNSAFE_componentWillReceiveProps
  3. UNSAFE_componentWillUpdate
1,componentWillMount (Old name will generate a warning in development mode)
2,componentWillReceiveProps(Old name will generate a warning in development mode)
3,componentWillUpdate(Old name will generate a warning in development mode)

17.0 only the new "UNSAFE_" lifecycle name can be used

  1. UNSAFE_componentWillMount
  2. UNSAFE_componentWillReceiveProps
  3. UNSAFE_componentWillUpdate
1,componentWillMount (It has been deleted and cannot be used)
2,componentWillReceiveProps (It has been deleted and cannot be used)
3,componentWillUpdate (It has been deleted and cannot be used)

When strict mode is enabled, React will list all class components that use unsafe life cycle methods and print a warning message containing the information of these components, as shown below:

Warning for ref API

React provides two ways to manage refs: the outdated string ref API and the callback function API. Although the string ref API is more convenient to use in both, it has some disadvantages, so the official recommends using callback.

You may have known the ref attribute of string type in the previous API, such as "textInput". You can access the DOM node through this.refs.textInput.

class MyComponent extends React.Component {
  render() {
    return <input type="text" ref="textInput" />;
  }

  componentDidMount() {
    this.refs.textInput.focus();
  }
}

React 16.3 adds a third option, which provides the convenience of using the string ref without any disadvantages.

Detect side effects

The lifecycle of the rendering phase includes the following class component methods:

  1. constructor
  2. componentWillMount (or UNSAFE_componentWillMount)
  3. componentWillReceiveProps (or UNSAFE_componentWillReceiveProps)
  4. componentWillUpdate (or UNSAFE_componentWillUpdate)
  5. getDerivedStateFromProps shouldComponentUpdate render setState
    Update function (first parameter)

Because the above methods may be called many times, it is important not to write code related to side effects inside them. Ignoring this rule can lead to various problems, including memory leaks and or invalid application states. Unfortunately, these problems are difficult to find because they are usually uncertain.

Strict mode can't automatically detect your side effects, but it can help you find them and make them more deterministic. This operation is achieved by deliberately repeatedly calling the following functions:

  1. class component's constructor, render and shouldComponentUpdate methods
  2. class component's lifecycle method getDerivedStateFromProps
  3. Function component body
  4. State update function (i.e. the first parameter of setState)
  5. The function component uses useState, useMemo or useReducer

context API warning

The outdated context API is error prone and will be removed in future major releases. It is still valid in all 16.x releases, but in strict mode, the following warning will be displayed:


Use of older versions

import React, { Component } from 'react';
import PropTypes from 'prop-types';

class App extends Component {
  static childContextTypes = {
    theme: PropTypes.string
  }
  getChildContext () {
    return {
      theme: 'dark'
    }
  }
  render() {
    return (
      <Toolbar />
    );
  }
}

function Toolbar (props) {
  return (
    <div>
      <ThemedButton />
    </div>
  )
}

class ThemedButton extends Component {
  static contextTypes = {
    theme: PropTypes.string
  }
  render() {
    return (
      <button>{this.context.theme}</button>
    );
  }
}

export default App;

Use of new version

import React, { Component } from 'react';
const ThemeContext = React.createContext('light');

class App extends Component {
  render() {
    return (
      <ThemeContext.Provider value="dark">
        <Toolbar />
      </ThemeContext.Provider>
    );
  }
}

function Toolbar (props) {
  return (
    <div>
      <ThemedButton />
    </div>
  )
}

class ThemedButton extends Component {
  static contextType = ThemeContext
  render() {
    return (
      <button>{this.context}</button>
    );
  }
}

export default App;

Keywords: React

Added by clicket on Sun, 10 Oct 2021 13:52:34 +0300