Contact Information

No. 1101, 24th Main, JP Nagar, 1st Phase, Bangalore 560 078

What is ReactJS State?

This chapter introduces ReactJS State. State is an updatable object that can be used to hold the data and to control the behavior of the Component. Only Class Components can have State, not the Functional Components. When the State is changed React will automatically re-render the component.

Consider the example from our previous tutorial. Change the Class component as below.

class ClassComponentExample extends React.Component {
  constructor(props){
      super(props);
      this.state = {
          messageB1:"Default Message B - 1",
          messageB2:"Default Message B - 2",
      }
  }
  b1OnClick = () =>{
      this.setState({
          messageB1:"B-1 Button Clicked :)"
      })
  }
  b2OnClick = () =>{
      this.setState({
          messageB2:"B-2 Button Clicked :)"
      })
  }

  render() {
      return 

{this.props.message}

{this.state.messageB1}

{this.state.messageB2}

} }
Now let’s recap what is going on.
  • ReactDOM.render function is called with <FunctionalComponent name={“Adam”}/> , <FunctionalComponentArrow course={“React”}/> and <ClassComponentExample message={“Welcome”}/> components.
  • React call FunctionalComponent with name = “Adam”, FunctionalComponentArrow with course = “React” and ClassComponentExample with message = “Welcome”
  • We can access functional component props using props.name.
  • FunctionalComponent returns <h1>Func Component Example Adam</h1>
  • FunctionalComponentArrow returns <h1>Func Component Arrow Example React</h1>
  • ClassComponentExample returns <h1>Class Component Welcome</h1> element but you need to use this.props.message to access props.
  • React DOM updates the above elements returned from the components.

Default Props

Now you must be wondering what happens when parent component does not pass any attribute to child component. You can check that. Change ClassComponentExample declaration inside render as shown below

<ClassComponentExample />
As you can see, there is nothing in front of Class Component since we are not passing any props.

You can set default property values for a component. If the parent component does not pass any values then component uses default prop values. You can declare default props as shown below.

ClassComponentExample.defaultProps = {
    message:"Default Msg"
} 
Add this code above export default App statement. Now ClassComponentExample checks for message property value from the parent component if it is not available then values from defaultProps are used.
  • When ClassComponentExample is passed to ReactDom.render(), React calls its constructor and initializes the State and props.
  • Then React calls ClassComponentExample component’s render method.
  • Component returns first <h1> tag with props values <h1> Welcome </h1>
  • Second and third <h1> tags are initialised with State’s default values, <h1> Default Message B – 1 </h1> & <h1> Default Message B – 2 </h1> respectively.
  • Second and third <h1> tags are initialised with State’s default values, <h1>Default Message B – 1</h1> & <h1>Default Message B – 2</h1> respectively.
  • As soon as the State variable is updated, React re-renders the Component.

Constructor in React

The constructor method is used to initialize the Component’s state and it is automatically called by React before any other methods (Lifecycle methods). You can write a constructor for a Component as shown below


constructor(){
	super();
//…. Other Statements
}

But if you want to access props from the parent component then

constructor(props){
	super(props);
//…. Other Statements
}

The first statement of the Constructor should be super() or super(props). The function super() calls the parent constructor and super(props) passes the props to the parent constructor.
NOTE: Before Using this.props call super(props)
If super(props) is not called then this.props object is not available(undefined) and it can lead to bugs.

Initialize State

Since the Constructor is the first method called, it is the right place to initialize the state variables. State variables can be initialized using the following syntax.


this.state = {
	name:value,
	name:value
	....
}

In our case, we have initialized 2 state variables messageB1 and messageB2.
this.state = {
           messageB1:"Default Message B - 1",
           messageB2:"Default Message B - 2",       
}

Accessing State in render()

You can access and print the State with curly braces {}. for example, {this.state.variableName}.

Updating States

You can update the state with this.setState(data,callback) method. Instead of modifying directly using this.state, we use setState() method. The setState function is asynchronous. So it is always better to have a callback. When the State is changed, React will re-render the component and updates DOM.

NOTE: Do not use setState in constructor
When setState function is called React re-renders the components. But the component has not been rendered since constructor is the first method called by React.
In our example, clicking the B1 Button will fire b1OnClick which updates the State, and Component will be re-rendered with updated State values. You can independently update State variables. React merges the object you provide with the current state.
b1OnClick = () =>{
       this.setState({
       	messageB1:"B-1 Button Clicked :)"
       })
}
If you click on B1 Button and B2 Button then you can see the following screen

Chapter 4 - Understanding ReactJS Props



Leave a Reply

Your email address will not be published. Required fields are marked *