Remember to learn about React from the Hooks Api. Remember to learn from the Hooks Api

As for what is Hook, I recommend you to read the official website carefully.

By the way, if you’re confused by the title, take a moment to read this article. On the contrary, if it is to see the title of the first time to reflect the conclusion, you can go to get the knowledge of other articles

So next no nonsense, straight into the long knife, to the point!

A preliminary study memo

Let’s first step into the world of React. Memo with an example

Dumb function component – No memo used

For a function component, not using react. memo is like a person with no brain

Let’s take a look at the Demo below

Click to access the Demo Let’s take a look at what happens in the diagram above:

  1. The page is loaded for the first time, and the App component and B component are rendered. The printing effect of the console is as shown in the figure above
  2. Click the button to change the value within the App component. Both the App component and the B component are updated

The problem is that, logically speaking, this should be the process:

  1. The page is rendered for the first time, the App component and B component are updated and printed separately
  2. The data inside the App component has changed so the App component is re-rendered
  3. There is no gross relationship between the changed data and component B, and component B remains unchanged without updating the rendering

But the ideal is very plump, the reality is very backbone. The fact that not only did the App component get updated, but the B component also got updated, which is not what we want, because the B component: I didn’t do anything, and then I have to put on my clothes again?

Cause of invalid render

So what is the cause of invalid rendering?

In a nutshell, it goes like this:

The function component itself has no ability to recognize the prop value, and each update of the parent component is equivalent to giving a new prop value to the child component. As a general component, he does not have the ability to prop separately. When he sees that others have updated it, he will also create himself, which will cause the problem in 🌰 above.

Put a brain on Han. – Use the memo to wrap it

Put a brain on a function component When we put a brain on a function component, we think like this

import React form 'react';

const FuncComponent = () = >{

	return <h1>Hot, hot</h1>
}

export default React.memo(FunComponent);
Copy the code

The mindless Render component like 🌰 above would not have happened

Try to makeThe demoLet go of the comment on the last line of component B in the

Then click the button again as above to see the console print:

Or Yep! Only updated App components, as expected!

So why did this happen

So this is not the end of it, let’s further heat up 🔥

Passion heats up – Explore further

We don’t know how to avoid invalid updates.

Performance optimization points in class components

I don’t know if you noticed that the Class component also has a function called PureComponent. It does exactly the same thing as memo.

To recap, we often use this notation in class components:

import React, {PureComponent} from 'react';

class Demo extends PureComponent {

	// Performance optimization points
	shouldComponentUpdate(nextProps, nextState){	
		// Always returns true by default
		return true; }render() {
		return <h1>Understanding applause 👏</h1>}}Copy the code

In general, PureComponnet and Memo use shallow comparisons of props to determine whether the component needs to be updated.

If we do not actively use PureComponent in a class component, we can manually determine whether the component is updated:

ShouldComponentUpdate in the life cycle, to compare the current PORps with the state value, and then return a Boolean (true or false) to determine whether the component is updated.

The PureComponent does this for us, so we can use it without having to manually write code to optimize it.

Memo function realization

Here is my guess: Memo works in the same way as PureComponent. From a developer’s point of view, since class components have such an optimization method, function components must also need a method of similar functionality to help reduce the workload of code optimization. Therefore, the realization of the two functions should be mostly consistent. The React PureComponent is used for a shallow comparison

function shallowEqual (objA: mixed, objB: mixed) :boolean {
  // React is used to determine whether two values are equal or not. It only encapsulates + 0 and -0, and NaN and NaN cases
  if (is (objA, objB)) {
    return true;
  }
  // Check whether it is an object type
  if (
    typeofobjA ! = ='object' ||
    objA === null ||
    typeofobjB ! = ='object' ||
    objB === null
  ) {
    return false;
  }

  // Compare two objects with the same number of attributes
  const keysA = Object.keys (objA);
  const keysB = Object.keys (objB);

  if(keysA.length ! == keysB.length) {return false;
  }

  // Compare the attributes and values of two objects
  for (let i = 0; i < keysA.length; i++) {
    if(! hasOwnProperty.call (objB, keysA [i]) || ! is (objA [keysA [i]], objB [keysA [i]]) ) {return false; }}return true;
}
Copy the code

This is the source code for shallow comparisons in React, and is the key to determining whether or not to update components in PureComponent and Memo.

The memo works with the useMemo and useCallback

In general, in project optimization practice, the Memo wrapped function components are used in conjunction with useMemo and useCallback

I’m not going to go into a long story about useMemo and useCallback, because there are plenty of good articles in the community that you can check out. I’ll just give you a brief introduction in English

useCallback

  const memoizedCallback = useCallback(
    () = > {
      doSomething(a, b);
    },
    [a, b],
  );
Copy the code

The return value is a function memoizedCallback, which is the one passed in as the first argument. The difference is that the return value of the function is memoized, keeping the reference to the function. There is no need to redeclare a function to change its reference address in memory when a component is updated.

Unless the dependency in the second parameter array is changed, the memoizedCallback that returns the value remains the same

Application scenarios

Often used when parent component A passes A function to child component B as A prop value

Parent component A:

import React,{ useCallback } form 'react';

const A = () = > {
	
	return (
    	// If you do not use the useCallback wrapper, the handleClick function will be redeclared every time A is updated, resulting in invalid updates for B
     	<B handleClick={ useCallback( () =>//doSomething,[x,xx]) }; ) ; } export default A;Copy the code

Subcomponent B:

import React,{ memo } form 'react';

const B = (props) = > {
	const { handleClick } = props;
	return <div onClick={ handleClick} >Humble little B online Diss</div>; }// The memo should be used together with the memo, otherwise the mindless B component will always assume that the prop value passed is a new one
export defaultMemo (B);Copy the code

useMemo

const memoizedValue = useMemo(() = > computeExpensiveValue(a, b), [a, b]);
Copy the code

It’s very similar to useCallback, except that useMemo returns a value instead of a function

The first argument to useCallback is the function whose return value will be memoizedValue)

Unless the dependency in the second parameter array is changed, this is the same value as the returned value

UseMemo can do everything useCallback can do, but it is recommended that each do his or her job

const fn = useCallback( () = > //doSomething , [x,xx])
/ / equivalent to
const fn = useMemo( () = > () = > //doSomething , [x,xx])
// Since the return value of useMemo is the return value of the first function, we can achieve the effect of useCallback by simply making the function with the first argument return a function
Copy the code

conclusion

If you’re a React user, I strongly recommend you take a look at the React website carefully. I’m sure a lot of React developers haven’t even gone through the basic documentation on the React website. Trust me, it’s a lot to learn, and it’s one of the most basic things you should do as a React developer

After all my articles will be published on the public account in addition to technology and life, we can search attention to support ~