Home > Software engineering >  About React Memo
About React Memo

Time:12-16

I am learning React.

There are several componentized buttons. When I click on one button, the other button components, including the parent component, are also re-rendered.

import { useState } from 'react'

const Button = ({ setState, text }) => {

  console.log(`${text} rendering`)

  return (<button
    onClick={e => setState(prevState => !prevState)}
  >
    {text}
  </button>)
}

const Page = () => {

  console.log('Page rendering')

  const [aaa, setAaa] = useState(false)
  const [bbb, setBbb] = useState(false)

  return (<>

    <div>
      <Button
        setState={setAaa}
        text="A button"
      />
      <pre>{JSON.stringify(aaa, null, 2)}</pre>
    </div>

    <div>
      <Button
        setState={setBbb}
        text="B button"
      />
      <pre>{JSON.stringify(bbb, null, 2)}</pre>
    </div>

  </>)
}

export default Page

If anyone has more information, we would appreciate it if you could enlighten us. Thank you in advance.

CodePudding user response:

Anytime you set state in a component, the component and all of its children we re-render. You could memoize the children by wrapping them in React.memo so that if their props don't change they don't re-render. However, that will increase the memory footprint of your app, so often it only makes sense to memoize components that are expensive/slow to re-render, and your Button component is fairly simple to render.

  • Related