What is UseState Hook??

A quick introduction to the React useState hook

Harsha
TheLeanProgrammer
2 min readAug 21, 2021

--

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

  1. Import useState Hook from React
  2. 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 the counterValue.
  3. Initialize the counterValueto zero by passing 0 as the only useState argument.
  4. When the user clicks, we call setCounter with a new value. React will then re-render the component, passing the new counterValue value to it

Don’t forget to follow The Lean Programmer Publication for more such articles, and subscribe to our newsletter tinyletter.com/TheLeanProgrammer

--

--