I want to execute a function in Child Component after props gets changed in the Parent Component without having to manage an extra state in Child/Parent.
<ParentCompoenent
myCallback={() => {}}
myList={['a','b','c']}
/>
ChildComponent.js
componentWillReceiveProps(nextProps) {
console.log(this.props.myList, '==', nextProps.myList); // Outputs ['a','b','c'] == ['a','b','c']
}
When I'm trying to console the nextProps in componentWillReceiveProps its giving the same result every time even after the props have been changed.
you have to use
componentDidUpdatein class components anduseEffectin Function components...componentDidUpdatelike this:componentDidUpdatewill runconsole.logevery time the new prop is different fromprevProps.and in
useEffectyou just add the props to its dependency:useEffectwill call that function every time the value of that prop changes.