Learning About UseState Hooks

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 = () =>  {

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('')

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)

We can see the updated state by writing:


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.

Fullstack Software Engineer | Musician | Food Lover | Coffee Addict