State & Props




Today I am going to talk about State & Props. Both are plain javascript objects and used to store data, but states are used to store information within the component, props are used to pass data to a component.

State

Let's talk about states first. States are owned by its component. It is mutable. There are two way to initialize states in a class component.


  • Initialize inside the constructor (default way)

You have to define your states inside the state object (this.state). Inside an object, we have to define properties as key, value pair. First key then value. You have define state name then give a default value for that state.

  • Directly inside the class

Here we are defining states directly inside the class.

Below is the way to define states inside functional components.


You have to use useState hook to define your states. First give your state name then a function name to update the state. After that you have to give default value for the state inside the useState().

You can access state inside your class component using this.state.<state name> (ex: this.state.currentData). In class component, you have to use setState method to update your state. Below is the way to use the setState method.


In setState method, you have to pass a object, inside the object you have to use your state name and the value as earlier. Be careful when you are using setState method, because setState is asynchronous. The way to handle is, pass a callback function to the setState method.



Props

Let's talk about props. Props means properties. Props are used send data to the component. Props are immutable. That means read only. Can be passed to parent to child. Below is the way to pass props.


When you are setting the child components, you can give any name for the property then you can assign a value to that property. You can pass any number of props to a component. 


You access props like above displayed way.

Comments

Popular posts from this blog

API Guidlines (PayPal Standard)