Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

usage of React.memo() inside components with prop functions

import React, { useState } from 'react'

const App = () => {
  const [count, setCount] = useState<number>(0);
  const [otherCount, setOtherCount] = useState<number>(0);

  const increment = () => {
    setCount((pre) => {
      return pre + 1
    })
  }

  const decrease = () => {
    setOtherCount((pre) => {
      return pre - 1
    })
  }
  return (
    <>
      <DecrementComponent decrease={decrease} />
      <br />
      <br />
      <IncrementComponent increment={increment} />
    </>
  )
}

const DecrementComponent = React.memo(({ decrease }: { decrease: () => void; }) => {
  console.log("DecrementComponent");
  return (
    <div>
      <button onClick={decrease}>Decrement</button>
    </div>
  )
})

const IncrementComponent = React.memo(({ increment }: { increment: () => void; }) => {
  console.log("IncrementComponent");
  return (
    <div>
      <button onClick={increment}>Increment</button>
    </div>
  )
})

export default App

**React.memo(), although I used React.memo(), when I clicked increment or decrement functions, two components were rendered.
But I think one component shoud be rendered in this senerio. Why were two component rendered ?
**

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

React.memo can only help if the props don’t change. But the increment and decrement functions change on every render, so the props are always changing. You will need to memoize those functions so that they don’t change.

const increment = useCallback(() => {
  setCount((pre) => {
    return pre + 1
  });
}, []);

const decrement = useCallback(() => {
  setCount((pre) => {
    return pre - 1
  });
}, []);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading