Skip to main content

Command Palette

Search for a command to run...

UseState Hook

Published
β€’2 min read
UseState Hook

What are hooks?

Hooks are basically meant to maintain state in ReactJS without writing a class component. Hooks are a new addition in React 16.8. There are various hooks in react for different purposes. Let us see what is a useState hook.

The useState hook

The useState() is a Hook that allows you to have state variables in functional components. so basically useState is the ability to encapsulate local state in a functional component. When thinking about functionality, useState allows thinking in two or more states. Then events are required to change the state from one value to another.

The useState cycle

state β†’ event β†’ state

Syntax

 const [state, setState] = useState(initialState);

Here
state - Name of the state
setState - The function eventually used to change the value of this state
initialState - The initial value of the state
The only argument we pass in useState is the initial state. useState returns two values, the current state and the function that updates the state.
useState() can only be used in functional components and not class components. We need to import useState from react in order to use it.

import { useState } from 'react'

Example

Increase counter on + button click and decrease counter on - button click and display the counter.

const [count, setCount] = useState(0);

Now we will define the setCount() function.

const increaseCount = () => setCount(count => count + 1);
const decreaseCount = () => setCount(count => count - 1);

Here we are passing the parameter as count to setCount() which on every call of increaseCount() gets incremented by 1 and of decreaseCount() gets decremented by 1.

<button onClick = {decreaseCount}> - </button>
<p><strong> {counter} </strong></p>
<button onClick = {increaseCount}> + </button>

Here on clicking - button every time, decreaseCount() function gets called and the counter is decreased by 1. On clicking + button every tine, increaseCount() function gets called and the counter is increased by 1. To display the counter, simply put the {counter} variable in HTML tag.
Output initially

Screenshot 2022-10-02 234741.png Output after clicking on - button one time and + button two times respectively

collage.jpg

This was all about the introduction of useState() hook in react. Congrats! After this article you are well known about how to use useState(), why to use useState() and many more basic concepts related to it!