React Props and State

What is React Props?

Props mean "Properties.". It is an object that stores the value of attributes of a tag and works similarly to the HTML attributes.

First take an HTML properties:

<h2 id="conclusion" class="large-description"><a href="#conclusion">Conclusion</a></h2>

In the above example, "h2" is an HTML tag that has multiple properties like "class", and "id".

In React,

<Add n1={2} n2={3} />

here n1 & n2 are the properties.


Here "name" & "Age" are "props".

Inside the "Child" component we can use the props like below:



These are read-only components. It is an object which stores the values. Props are immutable, so it is not allowed to modify them inside the component. It is used only for passing data from one component to other. Inside the components, dynamic data can be generated based on props.


What is React State?

It contains data or information or the current state of the component. It can change over time based on events or users' actions. On change of "State" component decide to "re-render" or not.

React does not recommend "changing" state only by reassigning the state. It suggested to use setState() method. The method is asynchronous by type. It takes two parameters, the 1st one is the previous state & 2nd one is called by method.

Inside the functional Component State can be declared in the below manner:


State can be changed by calling the function:



For "Class component", state can be changed this way:


Props vs State

PropsState
It is immutableIt is mutable
Child components can accessChild components cannot access
Props make components reusableIt cannot make components reusable.
Props are external and are controlled by rendersState is internal and is controlled by React Component
Allows to pass data from one component to other components as an argumentHolds information about the components
It can only be accessed inside the component but not modified by the component directlyIt can only be accessed or modified inside the component or by the component directly


Comments