Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React component not rerendering when props changes

Here are my 2 React components - Parent and Child

class ParentComponent extends Component{

 render(){      
    /* consultations comes from redux store 
    and looks like { consultation_id:123, date:10/12/2013 } */
   return(
    _.map(this.props.consultations,(consultation)=>{

      return{
        <ChildComponent consultation={consultation} />
      }
    })
   );
  }
}

class ChildComponent extends Component{

  render(){
  return(
    <div>this.props.consultation.date</div> 
  );
  }
}

My problem is that I have certain actions that modify the consultations object. For eg: the props.consultation.date changes in the parent component, but the child component does not re render to show the latest consultation date.

However, I noticed that if I send each item in the consultations object to the child component like <ChildComponent date={this.props.consultation.date} /> it rerenders when the date changes!

Any idea why React does not re-render components when props sent as an object change?

I could always do with the work around but wondering if this is a bug or am I missing something?

like image 877
Jogi Nayak Avatar asked Dec 21 '18 10:12

Jogi Nayak


People also ask

Does React component Rerender when props change?

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 component remount when props change?

To remount a component when a prop changes, use the React key attribute as described in this post on the React blog: When a key changes, React will create a new component instance rather than update the current one. The example below shows how the key attribute can be used.

Does React re-render if state changes?

As we already saw before, React re-renders a component when you call the setState function to change the state (or the provided function from the useState hook in function components). As a result, the child components only update when the parent component's state changes with one of those functions.

Does child component Rerender if parent state changes?

State changes in Child component doesn't effect on the parent component, but when a state of parent component changes all the child components render.


1 Answers

The solution is to change consultation={consultation} to consultation={...consultation}. I am still unsure why, but it works!

like image 119
Jogi Nayak Avatar answered Nov 10 '22 01:11

Jogi Nayak