Props and status in React

What is the difference between state and props in React?

In the React component,PropsIs the variable passed to it by its parent component.statusOn the other hand, it is still a variable, but directly initialized and managed by the component.

The state can be initialized through props.

For example, the parent component can include child components by calling

<ChildComponent />

Parents can pass props using the following syntax:

<ChildComponent color=green />

In the ChildComponent constructor, we can access prop:

class ChildComponent extends React.Component {
  constructor(props) {
    super(props)
    console.log(props.color)
  }
}

And any other methods in this class can be usedthis.props.

Props can be used to set internal state based on the value of the prop in the constructor, as shown below:

class ChildComponent extends React.Component {
  constructor(props) {
    super(props)
    this.state.colorName = props.color
  }
}

Of course, the component can also initialize the state without viewing the props.

In this case, there is no use, but it is conceivable to do something different based on the prop value, and it is best to set a state value.

The props in the child component should never be changed, so if something happens to change some variable, the variable should belong to the component state.

Props are also used to allow child components to access methods defined in the parent component. This is a good way to centrally manage state in the parent component to avoid the need for children to have their own state.

Most of your components will only display some information based on the received props and stayStateless.

Download mine for freeResponse Handbook


More response tutorials: