Is there a way to check what props changed (without storing old props elsewhere) inside componentWillReceiveProps
?
i.e.
componentWillReceiveProps (newProps) { if( /* newProps.profileImage is different to previous props */ ) /* do stuff */ }
ReactJS – componentWillReceiveProps() Method This method is used during the updating phase of the React lifecycle. This function is generally called if the props passed to the component change. It is used to update the state in response with the new received props.
While there's currently no React Hook that does this out of the box, you can manually retrieve either the previous state or props from within a functional component by leveraging the useRef , useState , usePrevious , and useEffect Hooks in React.
A component cannot update its own props unless they are arrays or objects (having a component update its own props even if possible is an anti-pattern), but can update its state and the props of its children.
componentDidUpdate gets called after every prop or state has changed.
Note that the function componentWillReceiveProps
is now deprecated. Quoting the official documentation:
If you used
componentWillReceiveProps
for re-computing some data only when a prop changes, use a memoization helper instead.
This refers to the case where the your check inside componentWillReceiveProps
was to avoid unnecessarily recomputing the same thing many times. In the linked blog post, it suggests caching the result of the expensive function so that it can be looked up, rather than recomputed. This can be done using a helper such as memoize-one.
If you used
componentWillReceiveProps
to “reset” some state when a prop changes, consider either making a component fully controlled or fully uncontrolled with a key instead.
Again, the linked blog post describes this in more detail, but in a nutshell:
props
to set the initial state, and then ignores all further changes to the props.In very rare cases, you might want to use the
getDerivedStateFromProps
lifecycle as a last resort.
This function receives (props, state)
and returns any changes to the state before render
is called, giving you the control to do whatever you want.
At the point in time that this lifecycle method is called, this.props
refers to the previous set of props.
To compare a single property foo
on the the new props with the same property on the old ones, you can just compare newProps.foo
with this.props.foo
. So in your example:
componentWillReceiveProps (newProps) { if( newProps.profileImage !== this.props.profileImage ) /* do stuff */ }
You can also loop through all the props to see what changed.
componentWillReceiveProps(nextProps) { for (const index in nextProps) { if (nextProps[index] !== this.props[index]) { console.log(index, this.props[index], '-->', nextProps[index]); } } }
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