Buildtide
Author: Hussain Mir Ali

I am interested in web and mobile technologies.

If you have any questions or feedback then message me at devtips@Buildtide.com.

ReactJS state hook demystified

What is the state hook?

The state hook in ReactJS works in a similar way as the 'state' object in a class component. So essentially when using the 'state' hook developers can have stateful function components.

The example code below shows the difference between using state object in React class component and state hook in a functional component:

Functional Component:

import React, { useState } from 'react';

function PriceControl() {

  const [price, setPrice] = useState(0);

  return (
    <div>
      <p>Current Price: {price}</p>
      <button onClick={() => setPrice(price + 1)}>
        Increase Price
      </button>
    </div>
  );
}

Class Component:

class PriceControl extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      price: 0
    };
  }

  render() {
    return (
      <div>
        <p>Current Price: {this.state.price} </p>
        <button onClick={() => this.setState({ price: this.state.price + 1 })}>
          Increase Price
        </button>
      </div>
    );
  }
}

In the above code snippet for functional component 'useState' hook can be used to instantiate a state variale similar to 'this.state' object in class components. Calling 'useState' will return the state variable 'price' and a function to updated that value 'setPrice'. The initial argument for 'useState' will form the value for 'price' variable. This way the stateless components can have state so now they are called function components. The initial state argument can be of any type like object, number and string.

Reading State:

// Functional component
<p>Current Price: {price}</p>

// Class component
<p>Current Price: {this.state.price} </p>

In functional components state variable can directly be read without using 'this' context in class components. So in the 'PriceControl' functional component state variable 'price' can directly be used but in class component it will be read using 'this.state.price'.

Updating State:

// Functional component
<button onClick={() => setPrice(price + 1)}>
    Increase Price
</button>

// Class component
<button onClick={() => this.setState({ price: this.state.price + 1 })}>
   Increase Price
</button>

Similar to class components which update the state using 'this.setState' API the function components can also update the state variable using the function returned from 'useState'. Considering the 'PriceControl' functional component 'setPrice' can be used to set the state variable and equivalent class component API would be using 'this.setState({price: })'.

Multiple state variables:

// Functional component
  const [price, setPrice] = useState(0);
  const [volatility, setVolatility] = useState(0);
  const [discount, setDiscount] = useState(0);
  const [riskParam, setRiskParam] = useState(0);

// Class component
 this.state = {
      price: 0,
      volatility: 0,
      discount: 0,
      riskParam: 0
    };

Components can have more than one state variable. In practice using multiple state variables in a functional component is as simple as using multiple 'useState' APIs and instantiating state variables.

Summary:

  • The 'useState' API can be used to manage the state variables inside a functional component similar to 'this.state' object in class components.
  • The variable and update function returned from 'useState' can be used to read and update the state variable respectively.
  • To instantiate multiple state variables 'useState' can be used multiple times.