useState() in React

In this post, you will learn about the useState Hook in React. We will understand what the useState Hook is and how to use it in React.

React Hook:

A hook is a special function that enables you to use state and other React features without creating a class.

What is useState in React?
React’s useState Hook enables you to add state to functional components. Before the useState hook, we had to turn a functional component into a class component if we wanted to add state to it after we had already written the functional component. However, we can now quickly add state to our already functional component thanks to useState.

The initial state is passed as an argument to the useState() Hook, which then returns the current state and a function to update it.

Now, let’s see an example to understand it better.

First, import useState.

import React, {useState} from "react";

Now, here’s a component for a simple counter.

import React, {useState} from "react";
import "./counter.css"



export default function Counter(){


    const [value, setValue] = useState(0);

    return (<div className="counter">
        <button className="counterBtn" onClick={() => setValue(value-1)}>-</button>
        <span className="counterValue">{value}</span>
        <button className="counterBtn" onClick={() => setValue(value+1)}>+</button>
    </div>);
}

Here, I created a counter with two <button> elements and a <span> to show the counter value.

You can see the above code that I called useState() with an initial value of 0. When useState gets called it returns the current value and a function to update it. Here, the counter value is in the variable value and the function to update the value is setValue(). I call this method every time one of the buttons gets clicked then, the UI gets re-rendered.

Output:

Initial value: 0

After clicking the add button 3 times

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: