why we need props and states in react js

This “props vs. state” question is pretty common for new frontend developers - they look so similar, but are used differently.

Prop Vs React



The state is a data structure that starts with a default value when a Component mounts. It may be mutated across time, mostly as a result of user events or it provides the bindings between UI and logic functions.A Component manages its own state internally. Besides setting an initial state, it has no business fiddling with the state of its children. You might conceptualize state as private to that component.

Initialize the state:
You can initialize the state into the constructor of component:

import React, { Component } from 'react';
class XYZComponent extends Component {
       constructor(props){
             super(props);
          this.state={
           stateName:''
        }
     }
         render() {
             return (
       <div>
           <p>{{this.state.stateName}}</p>
      </div>
    );
  }
}
export default XYZComponent;

How to use it.

<p>{{this.state.stateName}}</p>

For update the state value use setState() method.

updateState(){
this.setState({stateName: 'something'});
}

Props :

Props are a Component's configuration. They are received from above and immutable as far as the Component receiving them is concerned.A Component cannot change its props, but it is responsible for putting together the props of its child Components. Props do not have to just be data -- callback functions may be passed in as props.

<XYZComponent propsName='Some Value'/>

Here you can pass props value into the XYZComponent. You can pass any type value like string, object, array etc.

import React, { Component } from 'react';
class XYZComponent extends Component {

render() {
   return (
       <div>
         <p>{{this.props.propsName }}</p>
      </div>
     );
   }
}

export default XYZComponent;


Here you will get props value with the help of this.props.propsName. now it will print the value of props that is “some value”.

You can also set the value of props with the help of state for example:


<MyComponent propsName={{this.state.stateName}} />

It means you can also update the value of props every time with the help of the state.

Download the eBook of react js for beginners

ReactJS basically is an open-source JavaScript library which is used for building user interfaces specifically for single page applications...

Popular