useState Hook Explained

useState Hook Explained

useState

useState Hook is one of the crucial hooks in React. To build projects comfortably in React, you need to have a solid understanding of the useState Hook.

With the introduction of Hooks in React version 16.8, class components are no longer needed since hooks make it easy for functional components to access state and other react features. Hooks are only used in React functional components.

The React useState hook allows us to track state in a functional component. The useState Hook takes the initial state as an argument and returns an array of two entries.

Syntax

useState hook accepts an initial state and returns two values:

  • The current state
  • A function that updates the state
const [state, setState] = useState(initialstate)

The first value, the state is the current state, and the second value, setState, is the function used to update our state. You can name these variables anything of your choice i.e.

const [count, setCount] = useState(0) //where ‘0’ is the initial state

A function can be passed as an argument if the initial state has to be computed. The returned value of the function is used as the initial state. The first value, state is the current state and the second value, setState is the function used to update our state.

Const [sum, setSum] = useState(function computeSum() {5+5});

The computeSum() function computes the sum, and the result is set as the initial state.

Importing the useState hook

To use the useState hook, it has to be imported into our component as shown below:

import React, {useState} from 'react';

We are destructuring useState from react since it is a named import. After importing the useState from react, we can now use it in our component. Let’s understand with the help of an example.

Example:

import React, { useState } from "react";
import ReactDOM from "react-dom";

export default function FavoriteColor() {
  const [color, setColor] = useState("green");

  function changeColor() {
    setColor("red");
  }

  return (
    <>
      <h3>My favorite color is {color}</h3>
      <button type="button" onClick={changeColor}>
        Click
      </button>
    </>
  );
}
ReactDOM.render(<FavoriteColor />, document.getElementById("root"));

Explanation:

Updating the color directly i.e. color = “red” is not allowed. We must use the second variable which is the setColor function to update it. The color variable is initialized with color “green” as the initial state and the setColor function is used to update the color. Each time we click on the button Click, it calls the changeColor function which then updates the color to red.

What Can State Hold

The useState hook can be used to track changes on strings, numbers, objects, Booleans, arrays, and any combination of these. We can use multiple Hooks to keep track of each value i.e.

export default function Car() {
  const [brand, setBrand] = useState('Ford')
  const [model, setModel] = useState('Mustang')
  const [year, setYear] = useState(1960)
  const [color, setColor] = useState('blue')
  }

Alternatively, we can use a single state with an object.

Example:

import React, {useState} from 'react';
import ReactDOM from 'react-dom';

export default function Car() {
const [car, setCar] = useState({
  brand: 'Ford',
  model: 'Mustang',
  year: 1960,
  color: 'blue'
  });
return (
<>
<p>I own a {car.brand}. It is a {car.color} {car.model} from {car.year} </p>
</>
)
}
ReactDOM.render(<Car />, document.getElementById('root'));

When rendering our component, we need to reference the object and the property of the object since we are tracking a single object.

How to Update the Object and the Arrays in the State

When we update a state in objects and arrays, the all state is overwritten. What happens if you just need to update the model of the car? If we call setCar({model: “Everest”}), it gets rid of brand, year, and color from our state. To avoid this, we introduce the JavaScript spread operator.

Example:

import React, {useState} from 'react';
import ReactDOM from 'react-dom';

export default function Car() {
const [car, setCar] = useState({
brand: 'Ford',
model: 'Mustang',
year: 1960,
color: 'blue'
});

function updateModel() {
setCar(prevState => {
return { ...prevState, model: 'Everest'}
});
}
return (
<>
<p>I own a {car.brand}. It is a {car.color} {car.model} from {car.year} </p>
<button type = 'button' onClick = {updateModel}>Click</button>
</>
)
}
ReactDOM.render(<Car />, document.getElementById('root'));

Explanation

Since we require the current value of our state, we pass a function into our setCar function which receives the previous value. We then return the object, by spreading the prevState enables us to only overwrite the model.

I hope this was helpful in understanding the useState Hook.

Give a 👍 and follow me for more articles on React and JavaScript.