Understanding state in React.js


State and lifecycle of component is very powerful to make things work in a dynamic applications.

State

State is generally used in Stateful component. With the introduction of hook, we can add state in functional component as well now . The name of the hook is useState.

State is a JavaScript object which can be changed by user actions and adds dynamism to UI. Updating the data from server with the use of state is common use case.

Difference between state and props −

  • As we know props is a properties JavaScript object which hold information passed as an attribute to the component.
  • Props value are immutable and should not be changed inside the component.
  • State is mutable and It can be changed as per the actions.
  • State can be created as an object in class based component. To create state in functional component, we can use the useState hook.
  • State can be updated by side effects like server calls and event handlers.

Creating state in class

class Message extends React.component{
   constructor(props){
      super(props);
      this.state = { message: ‘hello’};
   }
}

Or

class Message extends React.component{
   state = {message:’hello’};
   constructor(props){
      super(props);
   }
}

Creating state in functional component

import React, { useState } from ‘react’;
function Message(){
   const [message, setMessage] = useState(‘hello’);
   //return statement
   return (
   );
}

useState gives two outputs 1. Variable message and 2. Setter method (here setMessage). Message is initialized with string hello.

Updating state

State should not be updated directly. All updates to state should be done with the use of setState method provided by react library.

this.setState({message:’welcome’});

the direct initialization of state is allowed only once in class or its constructor.

If we need to use the previous state or props in update of any properties then we can do it in asynchronous way as below −

This.setState( (prevState, props) =>(
   {
      message: prevState.message+’hello’  
   }
))

Updated on: 28-Aug-2019

275 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements