preface

Among react hooks, useMemo is also a basic hook, which focuses on performance optimization. In my understanding, it is somewhat similar to vue’s computed property. Today, in order to impress me and learn more deeply, I write down my understanding of useMemo here.

Here we first post the code and then enumerate it line by line.

type User = { name: String; age: number; }; const Home: React.FC = () => { const [name, setName] = useState<String>(""); const [user, setUser] = useState<User>({} as User); Const resUser = () => {console.log(" get user"); return user; }; const getUser = useMemo(resUser, [name]); const setUserInfo = () => { setName("jack"); setUser({ name: "jack", age: 26 }); }; Return (<div className="Home"> <Button type="primary" onClick={setUserInfo}> Memo </Button> <p> } {getUser. Name | | "" < / p > < / div >). };Copy the code

Analysis of the

  • Defines the User type, containing the name and age attributes, respectively
  • A functional component declares a Home component
  • Define two states, one name related state and one user information related state
  • First look at the HTML content returned by the component, which contains a Button and<p>The label. Among them<p>The tag containsgetUserMethod, while getUser is useduseMemoThe resUser method is cached to return the value in this method. As you can see, the value returned is an object of type User. But user is the default at first{}Empty object, so<p>The content of the element is “Here is: none”. thenuseMemoThe second argument to the update dependency array is the only one put in herename“, meaning as long asnameIf the state changes, it firesresUserThis method returns a new oneuserObject.
  • And then there’s the Button component, the click event issetUserInfoThis method does two things: it updates the name and it updates the User object. And because it’s updatedname, so it will triggeruseMemoCached methods, that is, are re-executedresUserGet the latest User object, and thensetUserInfoUpdate the user object, soresUserThe latest user is also returned. At this time<p>The content of the element is: “This is: Jack”

This is the end of the code analysis.

But if we call setUserInfo setName(” Jack “); Get rid of this line of code, so I’m not updating the name. Will the resUser method still be launched? The answer is definitely no. Because useMemo dependency update is the name change will trigger the corresponding method.

The benefits of this

To see the benefits of this, let’s write a code that can be implemented without useMemo and change the Home component code:

const Home: React.FC = () => { const [user, setUser] = useState<User>({} as User); const setUserInfo = () => { setUser({ name: "jack", age: 26 }); }; const resUser = () => { // ... other operate return user; }; const updateOther = () = > { // ... other state updated } return ( <div className="Home"> <Button type="primary" onClick={setUserInfo}> memo </Button> < p > here is: {resUser (). The name | | "no"} < / p > < Button type = "primary" onClick = {updateOther} > update other < / Button > < / div >). };Copy the code

Reference methods in Html like the one above. When you click the updateOther event to update the other state that will re-render the component, the resUser method will enter again. If you encounter complex logic, this is very performance unfriendly, and you must avoid the consumption of retrieving user information without changing the state of the user.

So once useMemo is used, the methods it contains must depend on some newer item to be executed again, or else the last cached value will be read. This is the benefit of useMemo in optimizing performance.

The last

The examples in this article may not be appropriate, but there are simpler ways to do it. Also better performance. However, I only wrote this technical post to strengthen my understanding of React Hook. It would be nice to understand that it can be better applied to the project. Of course, this is also the author of his own a little bad bad, a deeper understanding will be updated again.