DEV Community

James Macapagal
James Macapagal

Posted on

useState: The Hook Brings You Back

I have a new found appreciation for The Facebook.

image

Whoops, I meant, Facebook- I mean Meta.

While I've been a Facebook user so long I can remember the "The", nowadays, I'm fascinated by React, the amazing JavaScript based framework developed and maintained by Meta.

Specifically, I am truly amazed by the wonderful tool developed in React called useState

useState is a Hook, a special type of function with the specific purpose of helping developers maintain state changes in applications.

The purpose of this blog is to identify:

  1. Why State as a concept is important
  2. How useState works
  3. When useState is useful

useState of the Union


Before we jump right in, let's get philosophical and define what we mean by state.

What do we mean by, just the word, state, in real life?

If you said, Illinois, I would say: damn, I thought I turned off location services on my Facebook privacy...

they found me

Beyond a politically organized groups of peoples, when we say state, Webster's dictionary says:

mode or condition of being

It is what something is right now. It is also what something will be in the future. It's also what something was in the past.

For instance, right now in my iced coffee, I have ice. In the future, the ice will melt and become water.

In other words, the water is changing state. It's changing from one state (of matter) into another state.

whoa

Though basic, this is an important concept to understand, both in life and web development (which is obviously more important of the two).

When it comes to the technology, we want things to change.

We want things to change state.

We want to change the states of things.

vision change state

Without changing state, technology (and life) would really be boring.

No likes.
No Candy Crush.
Nothing.

A cold, dark, and boring Internet with static applications.

Thankfully, we have handy hooks like useState to make things easier for us.


Well, what even is useState and why should I care?


Well, first off, rude.

Secondly, fundamentally, useState is just another function.

A special type of function called a Hook, created by React.

According to React, Hooks are:

functions that let you “hook into” React state and lifecycle features from function components

useState basically lets developers use special logic and features, already written for us!

Let's think about how we might change the value of a variable in vanilla JavaScript:

let x = 0;
console.log(x)
>> 0
Enter fullscreen mode Exit fullscreen mode
function setX(){
 x = x + 1
}
Enter fullscreen mode Exit fullscreen mode
setX()
console.log(x)
>> 1
Enter fullscreen mode Exit fullscreen mode

Pretty straight forward.

We declared an initial value for variable (x = 0).
We performed an operation on that variable (x + 1).

We checked the value of that variable afterwards (x = 1).

But, what if I told you you can do those 3 lines of code in 1 line of code?


Enter useState


While there is some special magic that goes on under the hood, the basis of useState is still rooted within the same idea of maintaining a variable.

Like with many things in React, we need to import this tool before using:

import React from 'react';
import { useState } from 'react;
Enter fullscreen mode Exit fullscreen mode

However, the magic of useState is in its simplicity.

Again, useState is just a function, but it is a special function that returns an array of just two elements: a State Variable and a Setter Function which we can define via array destructuring.

For instance:

const [ count, setCount ] = useState(0);
Enter fullscreen mode Exit fullscreen mode

The State Variable's purpose is in its name: its the variable that we want to maintain our state within. So, count in the previous line of code would be analogous to x in our previous OG JS code.

The Setter Function is also exactly what it sounds like: it sets the State Variable. Again, analogous to setX in our previous example.

Finally, the useState() keyword invokes the Hook from React's vast library and then sets an initial value for our State Variable passed as a parameter to the function (in this case 0).

The difference in useState versus that of our OG JavaScript function is syntax.

We can use array destructuring to easily set these two items, State Variable and Setter Function, without needing to declare and redeclare the variables.

After declaring our two variables, we can then use them how we'd like in the rest of our code.

First off, we still need to define the Setter Function's purpose. In my above example, I created another function that I can call that will call my setter function.

   function increment (){
      setCount(()=> count + 1)
    }
Enter fullscreen mode Exit fullscreen mode

So now, every time I invoke increment, it will call setCount which will update count which will now be set to the new value!

No re-calling the variable or redeclaring needed.

And now we can use both the State Variable and the Setter Function (via that helper function!)

*But wait there's more! *

butwaittheresmore

useState will not only set our variables (and "func" on them too), it will also re-render any components (and any JSX/DOM elements) within those components.

Think about that. Just one component- not the entire page.

While this is in part thanks to React's virtual DOM, it makes for a more modular, cleaner, and prettier website.

Think about what you might need to do in OG JS to re-render a component with count.

  • Write some verbose function to keep setting your variables
  • Set and append ad nauseam all the HTML element with your new variables
  • Oh yeah, refresh the whole page

That already sounds like hundreds of lines of code for one element, not to mention if this needs to happen within other elements on a page or other pages.


The Hook Brings You Back


In conclusion, useState is revolutionary in its simplicity, efficiency, and application.

What probably would have been done with hundreds of lines of JavaScript (with a healthy dose of unnecessary HTML) can now be done with useState.

The useState hook, via some internal magic, a State Variable, and Setter Function, brings a component back to re-render whenever we need it to- all within an efficient, clean line of code.

In the words of the immortal song "Hook" by Blues Traveler, the Hook brings you back.

Sources:
Hooks Overview
Hooks System
React's virtual DOM

Bonus: If you really want to dive into the rabbit hole, this blog builds it's own React library and dives into how to write your own Hooks.

Top comments (1)

Collapse
 
batmanonwheels profile image
Devin Garcia

Thank you James, very cool!