How do I see what props have changed in React?

Viewed 321

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?

1 Answers

You 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.

Related