Sunday 5 January 2020

Introduction to State 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.

State is a mutable object.

Convention

  • State of component should prevail throughout the lifetime thus it must have some initial state and define in constructor of class.
import React from 'react';

class MyApp extends React.Component {

   constructor(props){
       super(props);
       this.state={
            title:"State Post"
            name: "Ashish"
       }
   }
   render() {
      return (
         <div>
            <Header/>
            <Content/>
            <p>{this.state.title}</p>
            <p>{this.state.name}</p>
</div> ); } } export default App;

    1. In Javascript, super() refer to parent class constructor. we cant use 'this' until called parent constructor or create instance. Super is called for inherit parent class properties through it.

     2. In super(), the props parameter is not mandatory. if we don't pass the parameter           the by default it will pass actual props in super()

     3. If you call any function before super() in constructor & use the property of parent           class then parent class property wouldn't work. 

     4. Constructor is called for initializing.

  • State should never be update explicitly. for updating state, we should use this.setState.
     this.setState({ name:'hello'});

  • State calls are asynchronous & react may update multiple state in a single go. value of state may not always generate the desired the output. so don't generate the value.
     this.setState({ count :this.state.count });   wrong way
  
     this.setState((preState, props) => ({
                    count:this.state.count     right way
                   });
     );

  • State updates are independent- We can set multiple attribute in single shot. It will update independently because of asynchronous.
     this.setState({ name:'hello', 'class':10 });

  • Default state is nothing but initialization of state in constructor in class. 


No comments:

Post a Comment