Explain to me like I'm Seven: React's useState HookπŸ€”

Explain to me like I'm Seven: React's useState HookπŸ€”

Β·

6 min read

Why don't we just use a variable, What is a hook anyway?

I asked myself when I first started to learn about the so-called "useState" hook which is a feature of a web framework you might've heard about named ReactJS.

When I started, I was super confused but it started making sense eventually. I'm going to structure this post that I anyone can understand it

Let's get our Hands Dirty 🀝

The best way to learn about programming is to dive straight into the code, So now I would want you to pull up your terminal and enter the following command

  • npx create-react-app your_app_name or use

  • yarn create react-app your_app_name if you prefer yarn

gif-1.gif

While everything's being set up for us, Let's discuss a little bit about how React works and what the hell this useState even is?

How does React works? βš™

In order to understand you need to understand useState you need to know how React works. For the sake of simplification look at the simple counter application below

The Javascript for this application looks like this

const button = document.getElementById("btn");
const number = document.getElementById("num")

let count = 0;

button.addEventListener("click", () => {
  count++
  number.innerHTML = count;
} )

Pretty simple in my opinion, Right? Umm... Well, you could say so for websites of this sophistication, but as you build more complex apps updating your frontend data by grabbing their IDs and then manipulating them seems just unviable. When you have dozens of data to update it's just a nightmare working with vanilla JS

React Uses a little something called Virtual Dom.

Terminology aside, To put it simply it React introduced Hooks with their version 16.0 including the useState hook that keeps track of your variable (also referred to as state), and Re-Renders your component whenever the data is updated.

I highly recommend you to understand and read about React's Component Life Cycle

You don't have to be a React saint to understand this, It's pretty simple actually

  • Your component attaches (or mounts) to the dom

  • It performs all the actions it is supposed to do like Updating

  • Unmounts or Removes itself from the page after it's done

One good way to visualize this will be to think of lego

image.png

The pink block is your page, Now another component is added/mounted to it πŸ‘€

Untitled design.gif

This blue block is our mounted state, Now it updates it may do its own thing maybe change color or add another block secong.gif

When the blue block has finished its task it has completed its lifecycle and our little friend unmounts ~poof!

image.png

Now you get the Idea, We shall talk more about component lifecycle in some future post

So now there is no need to use the number.innerHTML to update your data as in React whenever you're using a state it automatically re-renders whenever state changes

How do we make a State?

OKAY, React Guru! If you've bestowed all this information on meπŸ˜’ Now, tell me how do I make a state?

If you've made it this far, You probably would've guessed. Yes it is the useState() hook

Remember the react app we created? Let's go back there. If you see Happy Hacking! or something like that at the end of your terminal it means we're ready to go and react app is set up

Open the folder in an editor of your choice. I use VSCode The folder structure should look like this πŸ‘‡

image.png

Alright open app.js file functional component.gif and remove all the boilerplate code and create a functional component, run a local server (npm start or yarn start)

import React, { useState } from "react";

const App = () => {
  return (
    <div>
      <h1>Hello World</h1>
    </div>
  );
};

export default App;

If everything goes fine you will be seeing something like this

page-view.png

We can quickly copy the simple counter app UI

    <div>
      <h1>
        Count Status: <span>0</span>
      </h1>
      <button>Click Me</button>
    </div>

By adding some styles our app would look like this ui-looks.gif

It doesn't work yet, let's fix it!

Fun stuff starts nowπŸ˜ƒ

If you look at your code you will be able to see an import useState, If you're not familiar with the destructuring { useState } import format be sure to google es6 javascript

What is useState anyways? ~ it is just a simple function call that's all there is to it

Now it's time to create your long-awaited state, You have to explicitly define a state for react. if you just print the useState function call by console.log( useState() )

You would see this

image.png

An array containing a variable and a function

Index 0 is a variable, Index 1 is a function, We can use array destructuring in the syntax given below to easily access the function and the variable

look.png

The state is a variable but you can't change its value directly as it would not lead to a rerender, Therefore the useState function provides a function to use when you need to update the value

Thus,

let count = 0;
count += 1;
console.log(count)

Is almost identical to

const [count, setCount] = useState(0); || useState's parenthesis can contain any initial value 0 in this case
setCount(count + 1)
console.log(count)

The only difference is react would re-render our component and change the value of count wherever used on the UI automatically, Isn't that cool? Let's apply the functionality.

setState function could take in any value that you could store as a variable for eg Strings, Integers, Objects, Promises any data type containing value

Here's a small exercise for you

  • Make a state called count like we did before
  • Initialise it with 0
  • Create a function that would update Count

Solution πŸ‘‡

addition.gif

  const [count, setCount] = useState(0);

  const updateCount = () => {
    setCount((previousValue) => previousValue + 1);
  };

There's never a right solution in programming but that's how I would approach this, Also you can access previous state values with an anonymous function as shown above.

The question arises how do you access your span? Well, you can simply add { } curly braces in JSX to write javascript expressions and access your variables like πŸ‘‡

<h1>Hello, {object.name}</h1>

or maybe

<div>{var1 * var2}</div>

any valid js works inside curly braces, thus you can change <h1>Count Status: <span>0</span></h1> to <h1>Count Status: <span> {count} </span></h1>

To update the state you can add onclick event to the button and pass updateCount as a callback function

<button onClick={updateCount}>Click Me</button>

(Remember: Don't add () to your callback functions. parenthesis make an immediate function call and we don't want that )

Your FInal Code should look something like this

final.gif

Let's See Our Final Application

final-output.gif

Whoo!🎊 We did some really cool stuff today. You can go into detail and try to learn about useState function more, such as using them with forms, etc.

Try and play around with it and build stuff, If you build something cool you may also tag me on my Twitter

useState is one of the most common react hook that you're gonna use, In next blog probably we will be going into a lot of details with useEffect hook another useful React hook.

If you're interested in that article and other cool web dev related stuff, You can follow me here and also on my Twitter

Β