• Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Since I am currently working on the VUE project, it is easy to forget some knowledge when I don’t have to use React for some time (including the version upgrade of course), so I will summarize the react knowledge thoroughly.

  1. React16 life cycle

Constructor -> getDerivedStateFromProps -> Render -> componentDidMount

  • constructor: component constructor, the first to be executed. If no display defines it, we will have a default constructor. If the display defines a constructor, we must execute on the first line of the constructorsuper(props)Otherwise we can’t get this object in the constructor.
constructor(props) {
    super(props)

    this.state = {
      select,
      height: 'atuo',
      externalClass,
      externalClassText
    }

    this.handleChange1 = this.handleChange1.bind(this)
    this.handleChange2 = this.handleChange2.bind(this)}Copy the code

In constructors we typically do two things: 1. Initialize the state object; 2. Bind this to custom methods

  • GetDerivedStateFromProps: This function has two arguments, props and state, which refer to the new argument received and the current state object. This function returns an object to update the current state object, or null if no update is needed. This function is called at mount time and when new props are received.
  • Render: The render function is a pure function that does only one thing, that is to return what needs to be rendered, and should not contain any other business logic.
  • ComponentDidMount: Called after the component is loaded, at which point we can grab the DOM node and manipulate it. Calling setState in componentDidMount triggers an extra render, an extra call to the render function, but the user doesn’t know it because it’s executed before the browser has flushed the screen, but we should avoid it in development because it brings two performance issues. Instead of calling the state method at componentDidMount, we should initialize our state object in Constructor.

GetDerivedStateFromProps -> shouldComponentUpdate -> Render -> getSnapshotBeforeUpdate -> componetDidUpdate

  • GetDerivedStateFromProps: This method was described in the load phase and won’t be described here. Remember that in the update phase, this method is called whenever we receive a new property, call setState, or call forceUpdate.
  • shouldComponetUpdate: takes two parametersnextPropsandnextState, representing the state of the new property and the change, returns a Boolean value, true meaning re-rendering will be triggered, false meaning re-rendering will not be triggered, and true is returned by default. (This method is not triggered when we call forceUpdate)

    Because the default return is true, rerendering is triggered whenever a new property is received and setState is called, which can cause performance problems, so we need to mix this. Props with nextProps, And this.state is compared to nextState to determine whether to return false to reduce rerendering.
  • Render:
  • GetSnapshotBeforeUpdate: This method is called after Render componentDidUpdate, with prevProps and prevState, representing the previous property and the previous state. This function returns a value, Will be passed to componentDidUpdate as the third argument, return null if you don’t want it, console will warn if you don’t. Also, this method must be used with componentDidUpdate, otherwise the console will also be warned. Typical scenario: Get the DOM state before render.
  • ComponentDidUpdate: This method is called after the getSnapshotBeforUpdate method with three parameters prevPops, prevState, snapshot, which represents the previous props, the previous state, and snapshot. The third parameter is returned by getSnapshotBeforeUpdate. In this function we can manipulate the dom, initiate server requests, and setState, but be careful to use the if statement to control, otherwise it will cause an infinite loop.

Unloading stage: componentWillUnmount

  • ComponentWillUnmount: Called when a component is unmounted or destroyed, this function is used to clear timers, cancel network requests, clean up invalid DOM elements, etc.
  1. React virtual DOM and Diff algorithms

  • Virtual DOM: Working directly with the DOM triggers rearrangements and redraws, and creating the DOM directly can be time-consuming. Virtual DOM is the first dom rendering, an additional layer of virtual DOM calculation, on the basis of the DOM to establish an abstraction layer. When changes are made, a new virtual DOM will be generated and the last generated virtual DOM will be diff, wait for a differentiated patch, and then the patch will be typed into the browser’s DOM.
  • Diff algorithm: Two tree complete diff algorithm time complexity O(n^3). React applies three strategies that reduce the time complexity from O(n^3) to O(n). 2.1 tree diff hierarchy: Comparison layer by layer. Assuming that the probability of nodes being operated across hierarchies is not high, when encountering an old virtual DOM, if this node exists in the old virtual DOM but not in the new virtual DOM, this node will be deleted without being found across hierarchies. Component level: Two components of the same type have the same DOM structure, and two components of different types have different DOM results. If the components are different, delete and insert them directly. 2.3 Element diff level: For a group of nodes under the same parent node, they are marked by key values. If the keys are different, delete and insert them; if the keys are the same, move them.
  1. Is setState asynchronous in React?

    SetState appears to be asynchronous, but in fact it is not asynchronous in the true sense. It only simulates the behavior of asynchronous.

    3.1 In native DOM events and setTimeout, setState is updated synchronously.

    3.2 There is a policy to be followed in the composition events or hook functions, which will not be updated immediately, because the composition events and hook functions are run before the update.

  • React will maintain an isBatchingUpdates flag, which if false updates directly, and if true will temporarily queue the status.
  • And setState itself is not asynchronous, its execution process and code are synchronous, will not be updated immediately, because the synthesis event and hook function are run before the update, so it cannot get the updated value immediately, so the so-called “asynchronous” is formed, of course, the second parameter of setState can get the updated result. Or receive a function call, where you can get the result of the update.
  • In addition, React batch updates also have certain rules. If the same attribute is setState multiple times in a composite event or hook function, it will be overwritten with the latest one. If the attribute is setState multiple times, it will be combined with the batch update.