useMemo

Let’s use an example to understand the use of useMemo.

  • The parent component
function App() {
  const [name, setName] = useState('name')
  const [content,setContent] = useState('content')
  return (
      <>
        <button onClick={() => setName(new Date().getTime())}>name</button>
        <button onClick={() => setContent(new Date().getTime())}>content</button>
        <Button name={name}>{content}</Button>
      </>
  )
}

Copy the code
  • Child components
function Button({ name, children }) {
  function changeName(name) {
    console.log('11')
    return name + 'Method of changing name'
  }

  const otherName =  changeName(name)
  return (
      <>
        <div>{otherName}</div>
        <div>{children}</div>
      </>

  )
}
Copy the code

Students familiar with React can clearly see that when we click the button of the parent component, the name and children of the child component will change.

Notice how we print console.log.

Whether we change the value of name or content, we find that the changeName method is called. Does it mean that we only wanted to change the value of content, but since name has not changed, there is no need to perform the corresponding changeName method? But it turns out he did. Does that mean a loss of performance, a wasted effort?

Next we use useMemo for optimization

  • Optimized sub-components
function Button({ name, children }) {
  function changeName(name) {
    console.log('11')
    return name + 'Method of changing name'
  }

const otherName =  useMemo(()=>changeName(name),[name])
  return (
      <>
        <div>{otherName}</div>
        <div>{children}</div>
      </>

  )
}

export default Button
Copy the code

When we click on the change content button, we find that changeName is not called. But when the changeName button is clicked, changeName is called.

conclusion

Therefore, we can use useMemo method to avoid calling useless methods. Of course, useState may be used in changName to change the value of state, so as to avoid the second rendering of components and achieve the purpose of optimizing performance.