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.
React components automatically re-render whenever there is a change in their state or props. A simple update of the state, from anywhere in the code, causes all the User Interface (UI) elements to be re-rendered automatically.
Run useEffect When a Prop Changes useEffect can trigger on any of them. In this example, the PropChangeWatch component is receiving 2 props ( a and b ), and its effect will only run when the value of a changes (because we're passing an array containing [a] as the second argument).
We used the useEffect hook to update the state of a component when its props change. Copied! The logic in the useEffect hook is reran every time one of its dependencies changes. Every time the parentCount prop changes, the useEffect hook is reran and we use the setChildCount function to update the state.
you have to use componentDidUpdate
in class components and useEffect
in Function components...
componentDidUpdate
like this:
componentDidUpdate(prevProps, prevState) {
if (prevProps.something !== this.props.something) {
console.log('something prop has changed.')
}
}
componentDidUpdate
will run console.log
every time the new prop is different from prevProps
.
and in useEffect
you just add the props to its dependency:
useEffect(()=>{
console.log('something prop has changed.')
},[props.something]);
useEffect
will call that function every time the value of that prop changes.
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