[英]What to put in the dependency array in React.useMemo
Consider situation:考虑情况:
const App = ({ data = [], users = [] }) => {
const selectedId = React.memo(() => {
return data.find((id) => id === 'someId');
}, [data]);
const userIds = React.memo(() => {
return users.map(({ id }) => id);
}, [users]);
const finalIds = React.memo(() => {
return userIds.find((id) => id === selectedId);
}, []);
return finalIds.toString();
}
What should I put in the dependency array in finalIds
?我应该在
finalIds
的依赖数组中finalIds
什么?
Should I:我是不是该:
[data, users]
[data, users]
[selectedId, userIds]
[selectedId, userIds]
You put any variables that you use inside the calculation.您可以将您使用的任何变量放入计算中。 In other words,
[selectedId, userIds]
.换句话说,
[selectedId, userIds]
。 When those variables change, you need to repeat the calculation, or finalIds
will be stale.当这些变量发生变化时,您需要重复计算,否则
finalIds
将过时。
If you use eslint, i'd recommend using eslint-plugin-react-hooks .如果您使用 eslint,我建议您使用eslint-plugin-react-hooks 。 It can spot if you're missing a variable from the dependency array and fill them in automatically.
它可以发现您是否缺少依赖项数组中的变量并自动填充它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.