React Hooks Part 1: UseState

Devante Lowery
3 min readMay 13, 2021

Part 1 of a Series of Blogs on Hooks

Photo by Joshua Reddekopp on Unsplash

Introduction

As we know, one of the most important part of React is managing state. Before hooks were introduced the only way to modify state was with class components and this.state. As of React v.16.8, Hooks let you use state and other React features without writing a class. For this blog we’ll focus on useState. It’s similar to this.setState in a class, except it doesn’t merge the old and new state together. There are some important things to note before using hooks.

  1. Hooks can only be called inside of a function component
  2. Cannot be nested inside other things such as a conditional.

Importing

After creating a react app you’ll first have to change some code at the top by using:

Initial State

Here I’ve made a simple incrementing button and set useState to 0. The count = the current or initial state. The setCount is a function that takes a new value to update the state variable. The syntax used below is possible due to array destructuring.

The state is set to 0.

Updating State

Using setCount this way works but this is not the best way. The problem with this doing it like this is if you were to call it twice it would decrement only once due to overwriting the previous setCount function. A better way would be to use it like this:

Function Version

There’s also a function version of useState which can be useful when dealing with complex computation that would slow your application down. Instead of re-rendering every single time the component re-renders, it will only run once.

Using an Object Inside useState

Like I said earlier, useState is similar to setState but useState does not automatically merge. If you decide to use an object you must use a spread to update all your previous data so that it will not overwrite your other data.

While this does work what you’ll actually want to end up doing is using multiple useState hooks.

Using Multiple useState Hooks

Using multiple useState hooks as as easy as:

Overall, useState is a useful tool that any programer should take the time to learn.

--

--