Learning About UseState Hooks

Grace Yuiko Nakano
2 min readAug 10, 2021

Hooks that allow usage of state without class

Hooks give us the ability to use state in “stateless components”, also known as function components. You cannot use hooks in classes.

Hook is a special function that allows us to “hook into” React features.

import React, { useState } from 'react'

In classes, we usually initialize state in the constructor using ‘this.state’. However, in function components, we don’t have access to ‘this’ and hook into state by using ‘useState’

const TeamLike = () =>  {const [likes, setlikes] = useState('')...

Calling ‘useState’ declares a state variable, preserving the value between function calls. Typically, a variable disappears when the function exits but these variables are preserved as a React state.

The only arguments that we pass in ‘useState’ is initial state, which is not required to be an object like it is in classes. If you want to store multiple initial states, you would need to call useState multiple times.

UseState returns a pair of values, 1)the current the state 2)function that updates the state.

const [likes, setlikes] = useState('')// synonymous to 'this.state.likes' & 'this.state.setState'

We declare the state selectLikes and set the initial state to ‘ ’. To update the state, we call setSelectFile.

const incrementLike = (event) => {
let newlikes = likes + 1
return setlikes(newlikes)
}
return(
<div>
<p><strong>{likes}</strong> people have said you are amazing! </p>
</div>
)

We can see the updated state by writing:

<p>{selectLikes}</p>==> 1

Setting the state variables in an array is called ‘array destructuring’, the first variable returning the state and the second the setState. These useState hooks are extremely useful and allow us to easily access state and update state in functional components. Next week, I will discuss useEffect and how we can implement this hook when persisting data to local storage on the frontend.

--

--

Grace Yuiko Nakano

Fullstack Software Engineer | Musician | Food Lover | Coffee Addict