Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute a function after Props change

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.

like image 528
Neel Dsouza Avatar asked Feb 08 '21 07:02

Neel Dsouza


People also ask

What happens when props change React?

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.

Does useEffect run when props change?

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

Does state update when props change?

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.


1 Answers

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.

like image 194
Ali Hamedani Avatar answered Oct 12 '22 04:10

Ali Hamedani