reactjs - 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>
);
}
- 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?
解决方案
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
推荐阅读
- https - CouchDB 无法设置 HTTPS
- r - r - 将数据帧滞后 NA 的数量
- google-cloud-platform - 无法增加每个项目配额的数据流作业
- c# - 如何在 ContextMenu 中获取 PlacementTarget.Content?
- powershell - 将生成的价值传递给下游作业
- xaml - 更改 UWP RatingControl 的大小和间距
- xml - 使用 GetResourceText 加载 Office 功能区对象(按钮/组)时访问它们
- angularjs - 如何将值传递给指令?
- javascript - 阶梯区域谷歌图表错误的可视化
- oracle - 如何在 oracle 表单中使用带有 set_block_property 的游标?