Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React useMemo re-render issue

Tags:

reactjs

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>
  );
}
  • toggleVals is an boolean values
  • num is an integer
  • percentage prop is a floating point value

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?

like image 234
Kannaj Avatar asked Oct 15 '22 03:10

Kannaj


2 Answers

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

like image 156
Shubham Khatri Avatar answered Nov 15 '22 08:11

Shubham Khatri


in react we generally use React.Memo for your use case. wrap it around child component. you might be confusing it with React.useMemo . they are different. Using useMemo instead of React.memo syntax issue check that answer.

you can try something like,

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

export default React.Memo(RowVal).
like image 30
Ayyappa Gollu Avatar answered Nov 15 '22 08:11

Ayyappa Gollu