What is UseState Hook??
A quick introduction to the React useState hook
In React, functional components are basically stateless components as you cannot manage the state in them. But with the introduction of Hooks in React 16.8 version, If you write a function component and realize you need to add some state to it, you can use useState Hook.
Basically, useState lets you add React state to function components.
const [count, setCount] = useState()
count: the current state
setCount: a function that updates the state
This is similar to this.state.count
and this.setState
in a class, except you get them in a pair.
The only argument to the useState()
hook is the initial state. Unlike with classes, the state doesn’t have to be an object. We can keep a number or a string if that’s all we need.
const [count, setCount] = useState(0)
Below is the code snippet of a simple counter using class component.
Now consider we want to implement a similar counter in the functional component
- Import useState Hook from React
- Declare a new state variable by calling the
useState
Hook. It returns a pair of values,counterValue
which holds the number of button clicks,setCounter
which update thecounterValue
. - Initialize the
counterValue
to zero by passing0
as the onlyuseState
argument. - When the user clicks, we call
setCounter
with a new value. React will then re-render the component, passing the newcounterValue
value to it
Don’t forget to follow The Lean Programmer Publication for more such articles, and subscribe to our newsletter tinyletter.com/TheLeanProgrammer