1. Function component performance optimization

function MyComponent(props) {
  /* props render */
}
function areEqual(prevProps, nextProps) {
  /*
  如果把 nextProps 传入 render 方法的返回结果与
  将 prevProps 传入 render 方法的返回结果一致则返回 true,
  否则返回 false
  */
}
export default React.memo(MyComponent, areEqual);
Copy the code

Note:

Unlike the shouldComponentUpdate() method in the class component, areEqual returns true if props areEqual; If props are not equal, return false. This is the opposite of the return value of the shouldComponentUpdate method

The react. PureComponent class is optimized with the react. PureComponent, but its flaw is that it only updates the component when it recognizes data changes

Arrays and dictionaries can be changed to new data in the following ways so that subcomponents can refresh the array rewrite listener property

// Array adds fields
handleClick() {
  this.setState(state= > ({
    words: state.words.concat(['marklar'])}));// Optimize using ES6 extended operators
  this.setState(state= > ({
    words: [...state.words, 'marklar']})); }Copy the code

Dictionary additions change the original object

function updateColorMap(colormap) {
  colormap.right = 'blue';
  // Return a new object instead of modifying the old object
  return Object.assign({}, colormap, {right: 'blue'});
  / / ES6 syntax
  return{... colormap,right: 'blue'};
}
Copy the code

UI layer problem location is resolved

Use the React Developer Tools Components plug-in to screen out the error code blocks and directly locate the error code. Double-click to give the cause of the specific component error

The default data attribute of form. Item was incorrectly written. InitialValues should be used instead of defalutValues

Component performance optimization has three key cores

ShouldComponentUpdate is used to avoid redundant update logic

shouldComponentUpdate(nextProps, nextState)
Copy the code

The React component uses the return value of shouldComponentUpdate to determine whether to re-render the component after the lifecycle of the method. The default value is true, i.e. “unconditionally re-render”. Problem: In React, whenever the parent component is updated, all child components are updated unconditionally. Similarly, when it calls setState itself, it will go through the update process regardless of whether the state content before and after setState really changes

shouldComponentUpdate(nextProps, nextState) {
  // Determine whether the text property changed before and after the parent component was updated, or return false if it did not
  if(nextProps.text === this.props.text) {
    return false
  }
  // Updates are allowed to proceed only if the value of the text property does change
  return true
}
Copy the code

2.PureComponent + Immutable.js

Persistent data means that once it is created, it cannot be changed. Any modification we make to the current data results in the return of a new object. This strictly links changes in data content with references to data, making “change” invisible.

// Introduce a Map object in the IMmutable library, which is used to create objects
import { Map } from 'immutable'

// Initialize an object baseMap
const baseMap = Map({
  name: 'take it'.career: 'front end'.age: 99
})

// Use the IMmutable Api to modify the content of baseMap
const changedMap = baseMap.set({
  age: 100
})

// We will find that modifying baseMap will return a new object with a different reference from baseMap
console.log('baseMap === changedMap', baseMap === changedMap)

Copy the code

PureComonent and Immutable. Js are a pair of gay friends! In actual development, we often do PureComonent with our left hand and Immutable. Js with our right hand. Not all scenarios can be adopted as the optimal solution by the team. Therefore, it is a good idea for some teams to create public classes based on PureComonent and immutable.js that combine the two and improve the development experience by rewriting setState

3. The React. Memo and useMemo

Using useMemo allows us to have more fine-grained control over the execution logic of function components (especially to avoid costly calculations), as well as to compensate for the react.Memo’s inability to perceive the internal state of functions, which is a great benefit to our overall performance.

import React from "react";
// Define a function component

function FunctionDemo(props) {
  return xxx
}

// The areEqual function is the second input parameter of the memo, and the logic we put in shouldComponentUpdate can be transferred here

function areEqual(prevProps, nextProps) {
  /* return true if passing nextProps to render would return the same result as passing prevProps to render, otherwise return false */
}

// Use react. memo to wrap function components
export default React.memo(FunctionDemo, areEqual);

Copy the code

The react. memo will help us “remember” the renderings of the function components. If the components are the same as the props before and after, it will reuse the last renderings. The same thing we did in shouldComponentUpdate can now be done in areEqual.

PureComponent is equivalent to the React. Memo will automatically perform shallow comparison logic for your component. Unlike shouldComponentUpdate, The React.memo is only responsible for comparing props, and is not aware of changes in the component’s internal state.

In short, react. Memo controls whether a component needs to be rerendered, whereas useMemo controls whether a piece of logic needs to be executed repeatedly.

// Pass in the target logic as the first argument and the array of the logic's dependencies as the second argument. This way, useMemo reexecutes the target logic in the first entry only when one of the dependencies in the dependency array changes.
const memoizedValue = useMemo(() = > computeExpensiveValue(a, b), [a, b]);
Copy the code
import React,{ useMemo } from "react";

export default function ChildB({text, count}) {
  console.log(ChildB render logic executed);
  // text Render logic for text
  const renderText = (text) = > {
    console.log('renderText executes')
    return <p>Text content of child component B: {text}</p>
  }

  // render logic for count numbers
  const renderCount = (count) = > {
    console.log('renderCount executes')
    return <p>Numeric content of child component B: {count}</p>
  }
  
  // Use useMemo to add two pieces of render logic
  const textContent = useMemo(() = >renderText(text),[text])
  const countContent = useMemo(() = >renderCount(count),[count])
  return (
    <div className="childB">
      {textContent}
      {countContent}
    </div>
  );
}

Copy the code