Explain to me like I'm Seven: React's useState Hook🤔

Tags: react, javascript, webdev, programming
Published: 2021-12-13 04:45:04


> 
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 
![let's get our hands dirty]
(https://media.giphy.com/media/3htAT2no2D2ukVsUE2/giphy.gif)

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](https://cdn.hashnode.com/res/hashnode/image/upload/v1639156190736/14L_WhhG0.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

{%codepen https://codepen.io/krishna-bansall/pen/QWqKObW %}

The Javascript for this application looks like this

``` javascript
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

![cat falling](https://media4.giphy.com/media/3o85xkpCruOJPGtBMQ/giphy.gif?cid=6c09b95242451a15ad0697121ddaa73a12e4500a61bbe2ea&rid=giphy.gif&ct=g)

React Uses a little something called [Virtual Dom](https://reactjs.org/docs/faq-internals.html).

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](https://medium.com/codex/the-lifecycle-of-a-react-component-8e01332a068d) 

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](https://cdn.hashnode.com/res/hashnode/image/upload/v1639224833208/CUe-k9j7_.png)

The pink block is your page, Now another component is added/mounted to it 👀

![Untitled design.gif](https://cdn.hashnode.com/res/hashnode/image/upload/v1639225115563/9M6XZoyW9.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](https://cdn.hashnode.com/res/hashnode/image/upload/v1639225318647/tX_XB0KHB.gif)

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

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1639224833208/CUe-k9j7_.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](https://cdn.hashnode.com/res/hashnode/image/upload/v1639226964862/CZ-cFSbN-.png)

Alright open `app.js` file
![functional component.gif](https://cdn.hashnode.com/res/hashnode/image/upload/v1639227343441/VFQqZ6IGF.gif)
and remove all the boilerplate code and create a functional component, run a local server (npm start or yarn start) 
```javascript
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](https://cdn.hashnode.com/res/hashnode/image/upload/v1639227614332/Xet1DsjGo.png)

We can quickly copy the simple counter app UI
``` html
    <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](https://cdn.hashnode.com/res/hashnode/image/upload/v1639228655286/B-zVs6ufz.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](https://cdn.hashnode.com/res/hashnode/image/upload/v1639236401021/SHQRRztAf.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](https://cdn.hashnode.com/res/hashnode/image/upload/v1639231440467/TC-_wVmPL.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,
```javascript
let count = 0;
count += 1;
console.log(count) 
```
Is almost identical to 

```javascript
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](https://cdn.hashnode.com/res/hashnode/image/upload/v1639234576067/YXD9051mA.gif)

```javascript
  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 👇

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

or maybe

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

any valid js works inside curly braces, thus you can change 
``` html 
<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


```html
 <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](https://cdn.hashnode.com/res/hashnode/image/upload/v1639235522577/nZzDtDp2U.gif)

Let's See Our Final Application


![final-output.gif](https://cdn.hashnode.com/res/hashnode/image/upload/v1639235635148/_fEERq1jE.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 ](https://twitter.com/_TheChosenGuy_) 

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](https://twitter.com/_TheChosenGuy_)