How To Store Data Using useState

Introduction 

In this article, we will cover what is useState and how to use it in our application. So, let’s start.

What is useState?

The useState() is a Hook that allows you to have state variables in functional components. useState() is used to store/update data in function component and use it wherever required on the same component.

How to use useState?

Let’s create a simple component in our react js app and named it “UseStateExample.js” as below.

How to store data using useState

Let's try to use this component in App.js file and run the application using “npm start” and see the output.

How to store data using useState

Now, suppose we want to create a simple application that does increment and decrement and shows value like below.

How to store data using useState

So in this case whenever we click on increment button initial value should be saved and increase it by 1 and then again save it somewhere. Once we click on decrement, saved value should be decreased by 1 and save again.

We have multiple way to do it but, in this article, we will see how we can do it by using useState hook. It's very simple. So, let’s start.

Now update your UseStateExample.js component as below.

How to store data using useState

  • Import useState from react library.
  • useState()-> it return 2 argument one is current state and other is callback method (setCounter) to use if we want to update this state.
  • defaultValue -> useState() will take some default value to initialize the state.

This arguments name can be anything you like to give.

Now, how will use it? Every control will have one onClick handler. So we can use it.

Add a fat arrow function and use setCounter method to update counter as you want.

How to store data using useState

Code

import React , {useState} from 'react'
function UseStateExample(){
    const defaultValue = 0;
    const[counter, setCounter] = useState(defaultValue);
    return (
    <div>
        <h3>Example Of Use State</h3>
        <button onClick = {() => setCounter(counter+1)}>Increment</button>
        <button onClick = {() => setCounter(counter-1)}>Decrement</button>
        <p>{counter}</p>
    </div>
    )
} 
export default UseStateExample;

That’s it. Now just run the application and click on increment and decrement button to verify it.

How to store data using useState

As we see default value is set to “0” because we have given a deaultValue. Now click on increment and decrement to see change.

I just click Increment 4 times and we can see its getting updated.

How to store data using useState

Summary

This article covered how to use useState hook to update and store data. We have many ways to do it. In this article, we used useState, and in the next article, we will see same example using useReducer hook.

Make sure you don't just read through – go build, too.