A Noob Guide To useState()

A Noob Guide To useState()

What is useState???

Well in simple terms useState is a Hook, the first image that will come in to your mind after reading the word Hook will be the fishing Hook which is used to catch the fishes.

You are somehow right this useState Hooks does the same thing but in different manner, let's have a look at the working of the Hook.....

The useState() is a Hook that allows us to use have State Variables in Functional component. As we all know React ha two type of components one pf them is a Class Based components, and the other one is a Functional component.

How to declare useState in React??

To declare useState in React we have to export it from React, for this we have to do

import { useState } from 'react';

or another way of doing it is

React.useState

However, the first approach is always best to use in React.

Applying the Hook!!!

To understand this basic concept we will look at following example....

import React {useState} from 'react';

const stateTutorial = () => {

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

const increment = () => {
setCounter(count+1);

}

const decrement = () => {
setCounter(count-1);
}

 <div>{count}<button onClick={increment} >Increment</button> <button onClick={decrement}>Decerement</button> </div>

 )

}

Understanding The useState Hook!!

As we can see, we have imported the useState hook at the top of the file, Moving further we have a rendering Increment and Decrement button and a count text in between. This count will render every time the state gets updated by button clicks.

The useState Hooks takes an initial state , Count in this case and returns a pair of variables , Count and setCoutner is the current state (currently set to 0) whereas setCounter is a function which updates it asynchronously.

Further both button has an onClick event, which triggers a function , which increments and decrements the count variables using the setCount function. This clicks even results in the re-rendering of the count state.

Multiple states in a Single Component.

Well handling of multiple state variables is somehow different in useState compared to this.state, In useState we tend to write as many states like this,

const [lastname, setLastname] = useState(null)
const [firstname, setFirstname] = useState(null)
const [age, setAge] = useState(0)

Or group similar things together using an initial object,

const [islogin, setIslogin] = useState({
    username : "",
    password : ""
})

Why someone should use a Hook??

  1. Easier To Test.

  2. Provides good readability.

  3. Performance boost.

  4. Reduction in bundle size.

Conclusion.

React is now flexible thanks to Hooks. Most especially, it’s thanks to useState that we no longer need to rely on class-based components just to construct our UI Components. Hope I have covered as much as possible on useState.