admin管理员组文章数量:1202044
I am looking to make some performance improvements to my React components.
If I have a component that is called like:
<MyComponent
anObject={someObject}
aFn={someFn}
aValue={value}
/>
React will only "re-render" that component if anObject
, aFn
, or aValue
has changed. If I know my function is re-rendering, how can I tell which of those three props caused it?
I know I can console.log
aValue
and see if it changes, but what about the object and the function. They can have the same values but be referencing different memory. Can I output the memory location?
I am looking to make some performance improvements to my React components.
If I have a component that is called like:
<MyComponent
anObject={someObject}
aFn={someFn}
aValue={value}
/>
React will only "re-render" that component if anObject
, aFn
, or aValue
has changed. If I know my function is re-rendering, how can I tell which of those three props caused it?
I know I can console.log
aValue
and see if it changes, but what about the object and the function. They can have the same values but be referencing different memory. Can I output the memory location?
2 Answers
Reset to default 16You can use a useEffect
hook for each prop:
const MyComponent = ({ anObject, aFn, aValue }) => {
React.useEffect(() => {
console.log('anObject changed');
}, [anObject]);
React.useEffect(() => {
console.log('aFn changed');
}, [aFn]);
React.useEffect(() => {
console.log('aValue changed');
}, [aValue]);
// Your existing component code...
};
When the component mounts all three effects will run, but after that the logs will reveal what specifically is changing.
To add to the existing answer, I created a simple utility hook for this purpose.
function useWhatChanged(props: { [prop: string]: unknown }) {
// cache the last set of props
const prev = React.useRef(props);
React.useEffect(() => {
// check each prop to see if it has changed
const changed = Object.entries(props).reduce((a, [key, prop]: [string, unknown]) => {
if (prev.current[key] === prop) return a;
return {
...a,
[key]: {
prev: prev.current[key],
next: prop,
},
};
}, {} as { [k: string]: any });
if (Object.keys(changed).length > 0) {
console.group('Props That Changed');
console.log(changed);
console.groupEnd();
}
prev.current = props;
}, [props]);
}
function MyComponent(props: Props) {
// Pass an object of variables you want to check for changes
useWhatChanged(props)
}
Then just check the console to see which of the props have changed as well as their previous and current values.
本文标签: javascriptHow do I see what props have changed in ReactStack Overflow
版权声明:本文标题:javascript - How do I see what props have changed in React? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738642813a2104411.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论