Thursday, June 4, 2020

What is props and state in react

Ans:
Props

  • The props are read-only properties we set values to when we call our React component. 
  • They are a way to transfer information from the parent component to the child. 
  • We can also use them in your React component to control how it behaves in different situations – when different kind of data is passed down to it.
State

  • The state can also be used for controlling, e.g., how our component is rendered. 
  • What makes state different from props is that we can change its values.
  •  We typically initialize state with null values in the constructor and later change the values when something happens in the component to reflect that change – the new state of the component.

Remember when  render() method is executed whenever the props or state changes? we can change the state by calling the this.setState() method, and that will make our render method execute again, taking into account the new state values. There is also another way to set state: this.state = { ... } but that should only be used in the constructor as it does not trigger the render method execution.

No comments:

Post a Comment