Sunday 5 January 2020

State vs Props in ReactJs



State

State of component is an object that holds some information that may change over the life time of component.we can share the data from state in single class component.

A state is a variable which exists inside a component, that cannot be accessed and modified outside the component and can only be used inside the component. Works very similarly to a variable that is declared inside a function that cannot be accessed outside the scope of the function in normal javascript. 

State is a mutable object

class FakeComponent extends React.component{
  state = {
      name : 'Mukul';
   }
  render(){
      return <div>Hello {this.state.name}</div>
   }
// simple js function
const FakeFunction = () => {
  let name = 'Ashish';
  console.log(`Hey ${name}`);
}


Props

Props are basically one kind of global variable or object. react allows us to pass the information to other component using props and passing value will be either state value or as a argument.

A simple component and then we passes the props as attributes and then access them inside our component using this.props. So props makes components reusable by giving components the ability to receive data from the parent component in the form of props.


Props are immutable object.


// component 
class FakeComponent extends React.component{
 render(){
    return <div>Hello {this.props.name}</div>
    }
}
// passing the props
<FakeComponent name='Alice' />
<FakeComponent name='Joy' />



  • State can be used inside the class component & props doesn't have this limitation.
  • Props are set by parent component but state are set by event handler.