DEV Community

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

Collapse
 
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;
    dogs.push(dog);
    this.setState({dogs: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
    dogs.push(dog);

    // Now `dogs` has a new reference and React will re-render `Dogs` component
    this.setState({dogs:dogs});
  }

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.

css-tricks.com/how-react-reconcili...