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?
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
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With