首页 > 解决方案 > React useMemo re-render issue

问题描述

Im trying to use react-useMemo to prevent a component from re-rendering. But unfortunately, it doesn't seem to solve anything and im beginning to wonder if im doing something wrong

my component looks something like this

function RowVal(props) {
  console.log('rendering');
  return (
    <Row toggleVals={props.toggleVals}>
      <StyledTableData centerCell>{props.num}</StyledTableData>
      <StyledTableData centerCell borderRight>
        {props.percentage}
      </StyledTableData>
    </Row>
  );
}

In order to prevent the re-render - i added the below to my parent component

function ChainRow(props) {
 const MemoizedRowVal = useMemo(
    () => (
      <RowVal
        num={props.num}
        percentage={props.percentage}
        toggleVals={props.toggleVals}
      />
    ),
    [props.toggleVals],
  );

  return (

   <div>{MemoizedRowVal}</div>
  )

}

But this component still keeps re-rendering despite there being no change in the boolean value.

Is there something im doing wrong?

标签: reactjs

解决方案


useMemo will prevent a new instance of the component being created and will not stop it from re-rendering if props didn't change

I think what you need is to use React.memo and not useMemo

function ChainRow(props) {

  return (

   <div>
      <RowVal
        num={props.num}
        percentage={props.percentage}
        toggleVals={props.toggleVals}
      />
    </div>
  )

}

const RowVal = React.memo((props) => {
   // rowVal code here
});

React.memo also provides a second argument(areEqual) which you can use to have a more fineGrained control on re-rendering


推荐阅读