DEV Community

Discussion on: Stuck on the meaning of this.props.addDog(this.state.newDog)

giuseppe profile image
Giuseppe Author • Edited on

Ok, I've just found the meaning.
It creates a new dog item, sets the state of the child and passes to the parent component the state of the child to the prop addDog that will fire the bound function handleAddDog in App.js.

dance2die profile image
Sung M. Kim

Yes. I think you got it.

React has one way data flow.
So when you want to pass child component's data (a new dog) back to the parent (which is the one that maintains the list of dogs), you pass a callback to the child component, which will call the handler with the newly created dog object.

Simply put, this.props.addDog passes form data back to App component.

I've spotted a bug in App.handleAddDog, in which you are mutating the this.state.dogs by pushing the dog to the state directly.

You should not mutate the state object directly as React would not know if the this.state.dogs has not changed.

So instead of

 handleAddDog(dog) {
    let dogs = this.state.dogs;

create a copy (a new reference of dogs) and set it as a new state.

 handleAddDog(dog) {
    // This will create a copy of `this.state.dogs`
    const { dogs } = this.state;
    // or you can do
    const dogs = {...this.state.dogs};
    // then push the `dog` to the new dogs state object

    // Now `dogs` has a new reference and React will re-render `Dogs` component

The reason for passing a new reference of dogs is an advanced concept on how React reconciles changes.

Simply put, it's for React not having to do deep property change checks

If you want to know more on how React reconcilation diff'ing algorithm works, check out this post.