A Complete Guide to useState Hook in React | Beginner to Advanced Level

A Complete Guide to useState Hook in React | Beginner to Advanced Level

Learn to Manage State in Your Functional Components Using useState Hook in React 16.8 and Above | Best Practices and Examples Included

React is a popular JavaScript library for building user interfaces. One of its key features is the ability to manage state using "hooks". Hooks are functions that allow you to "hook into" React features like state, lifecycle methods, and context.

One of the most commonly used hooks is "useState". It allows you to add a state to your functional components. Before the release of hooks, the state could only be managed using class components in React. But with the introduction of "useState" hook in React version 16.8, state management became possible in functional components as well.

"useState" hook is a powerful tool for managing the state in functional components. It makes it easy to add and update the state without having to convert your component into a class. With "useState", you can easily create dynamic and interactive user interfaces in React. "useState" hook is a function that returns an array with two elements: the current state value and a function to update that value.

EXAMPLE

We will learn through an example of how "useState" works in React:

Let's say we want to build a simple counter app that starts at zero and allows the user to increment or decrement the counter by clicking a button.

First, we need to import the "useState" from the React library:

import React, { useState } from 'react'
// fun fact: you neednot import 'React' in the latest versions of react, so this line could also look like:
// import { useState } from 'react'

Next, we can use the "useState" function to create a new state variable called "count" that starts at zero:

const [count, setCount] = useState(0)
// ALWAYS define your hooks on the top level inside your functional components.

The useState function returns an array with two values: the current value of the state variable (in this case, zero), and a function to update the state variable (in this case, "setCount").

Now let's make a simple JSX file containing 2 buttons for increasing and decreasing the count. Also, let's display the count in the middle.

<div>
  <button>-</button>
  <span>{count}</span>
  <button>+</button>
</div>

Now let's add some onClick event handlers to the buttons.

<div>
  <button onClick={() => setCount(count-1)}>-</button>
  <span>{count}</span>
  <button onClick={() => setCount(count+1)}>+</button>
</div>

onClick takes in a function which then calls the setCount function. The setCount function changes the value of the count by decreasing or increasing the current count. The {count} inside the span then changes as the page renders the new state of count from the hook.

There you got yourself a basic counter using the useState hook of react.

This is all you need to get started but you can also read further for a better way.

Better Way

Now I want you to learn a better way of using useState. Let us continue with the same example as before. While using the setCount function, it's always a better practice to use the functional version of it.

Lemme clarify it with code. So here I am tweaking the above example's code a little bit. I am extracting the function from the onClick and store it inside a variable. Then I will give a reference of those to the onClick.

<button onClick={sub}>-</button>
<span>{count}</span>
<button onClick={add}>+</button>

Then the function sub and add will be defined like this:

const sub = () => {
  setCount(count-1)
}
const add = () => {
  setCount(count+1)
}

Up to now, there's been no change in the logic of the code.

Now the way of using a functional version of the setCount looks like this:

const sub = () => {
  setCount((currentCount) => {
    return currentCount - 1
  })
}
const add = () => {
  setCount((currentCount) => {
    return currentCount + 1
  })
}

We are giving in a function inside the setCount. That function can receive the current value of the state. We named it currentValue and then the function returns the new value after increasing or decreasing the current value.

Now, you might ask what was the problem with the previous code.

Well, if you again need to change the state i.e. value of count using the useCount function anywhere else in the code again, it won't work. Try copying it down twice in the previous example. You would expect it to decrease or increase the count by 2 but that won't happen because what you are doing is passing the same value of count both times as the value of count is the same for both. This can be avoided using the functional version. Build a habit of using it. It's very helpful.

Hope you learned something new today.

Happy Coding!