Understanding useState Hook in 3 min

Use state without writing a class.

Sushil Kumar
Codewords
3 min readJun 14, 2019

--

First, Hooks!

A Hook is a special function that lets you “hook into” React features.

In simple terms, Hooks are functions that make React state and lifecycle features accessible without writing any class component.

Basic Hooks include useState, useEffect, and useContext. For this article, we will focus on the useState hook and explore how to declare, read and update state variable in a functional component with the useState hook.

useState Hook?

You might have faced an issue where you would have written a functional component and realized that you need to add some state to it and then ended up converting it to a class component. Well, not anymore. State hook is here to the rescue.

usestate is the Hook that lets you “hook into” React state. With the help of useState hook, a state can be added to a functional component.

Let's take an example where we initialize a state variable count to 0 in a functional component by calling a usestate hook.

Now let's understand what exactly const [count, setCount]=useState(0); is actually doing.

  • Calling useState will declare a count state variable.
  • The only argument to the useState() hook is the initial state. So here we are setting the initial state of count to 0.
  • The useState returns pair of values: the current state and a function that updates it. With the help of array destructing, count is set to the first value returned by useState and setCount to the second. This means the current state is assigned to count whereas the function that updates the state is assigned to setCount.

You can declare multiple state variables with useState hook.

Reading State

Reading state in a functional component is straightforward. You can directly use the count state variable that you declared earlier, with the help of a useState hook.

Updating State

If you remember, the second value returned from the useState hook is a function that updates declared state variable. So you can directly use setCount to update the count state.

However, unlike this.setState in a class, updating a state variable always replaces it, instead of merging it.

Note: Before using hooks read “Rules of Hooks”.

That's it!.

--

--

Codewords
Codewords

Published in Codewords

This publication by Launch Ventures is an attempt to help the software engineering community write code that people enjoy reading.

Sushil Kumar
Sushil Kumar

Written by Sushil Kumar

FED | Red Panda Innovation Labs