UseState can be considered as the most important & common used react hook. It allows us to change state of variables in react functional components. Usestate was introduced around 2018 with all other hooks to make react development easy & shift from class based approach to functional based approach. Therefore, all the hooks including useState can only be used with functional components & not with class components.
To use useState in react with functional components we must import it first.
import { useState } from "react";
After useState has been imported from react in order to use useState we have to initialise a state variable with the initial state.
const [name, setName] = useState("donald")
//const [state, setState] = useState(initialState)
As shown in the above syntax here name will be our state variable which we will access within our functional component & setName is the function which will be used to change the state variable name's value. Inside useState a string is given which is an initial state which we will get at the very first time when we access the state variable name before modifying it.
Here in the above code, you can observe that we have initialised state variable counter with initial state 0 & then on click of a button we are incrementing it using the setCounter function provided by useState. Here on click of a button setCounter will asynchronously increment our variable. But using the state in the above way can cause problems because it's async. Let's try to understand the problem using the example below.
As shown in the above program we are incrementing the counter twice using setCounter on every click but on the UI is it only getting incremented by 1. Because every time when we are executing the function given on onClick handler the setCount is taking the same count value for both its operations. So, to solve this problem we can use functional state update as demonstrated below.
As shown above here instead of using state variable counter to update itself we are using functional state update & when we use functional state update we will get the current state as an argument to the setState function. So, using the functional update for the useState problem due to its async nature can be tackled.
End Notes: Hope you like the blog. If you have any suggestions please feel free to comment. Happy Coding! Good Day!