React Basics: State and useState
Starting your adventure with React, which is currently one of the most widely used frameworks, you will come across the concept of state and the accompanying useState hook which may be incomprehensible to beginners. In this article, I will explain what it is all about using simple language.
What is a state?
This is one of the questions you may ask yourself at the beginning of your study, but also one you may hear during your job interview, so read a few definitions and… rewrite yours, because understanding the concept of state is crucial in your study.
According to my definition state is all data (texts, numbers, objects, arrays) that define the functionality of our application (or its parts) and how it works.
The simplest example of a state? Mobile Menu, which you can find on most websites. Here is a pseudo-code that will help you understand what I'm writing about. Our state is the variable “openMenu”.
```
openMenu = false
The toggleMobileMenu {
if openMenu is false {
Change openMenu to true
} if openMenu is true {
Change openMenu to false
}
}
If openMenu === true, open MobileMenu
```
And with this code, you can open and close the menu.
The toggleMobileMenu should be attached to a button, which in the jargon is called "hamburger menu".
Other, more complicated examples of a state? For example, logged-in users, or data downloaded from API, but don't worry about it. Right now we focus on the basics.
What are Hooks?
The first issue worth mentioning is the "hook". The official React documentation describes it as:
Hooks are functions that allow you to "hook" into React's state and lifecycle mechanisms from within functional components. Hooks don't work in classes - instead, they let you use React without classes.
Link: Hooks at a Glance
Let's be honest - when you start your adventure with React and read the documentation the first time - you don't get any of it. This is normal. State, life cycle, classes. Lots of new concepts are hard to understand at the beginning, so for now, let's focus on the things that will allow us to understand the basics. Let's bring it to my simplified definition.
Hooks are functions that are the trademark of React. They allow us to manipulate our website/application/state somewhat behind our backs, without in-depth knowledge of how it happens. We have hooks for state management, component updates (i.e. separate pieces of code, such as navbar or modal), code optimization. There are many of them, but two are enough to get you started: useState (more on that in a moment) and useEffect.
How to use useState?
useState hook helps us control the state of our application. To use it, we need to start by importing it. The easiest way to do this is at the very top of the code. You import the hook in every .js file you want to use it in. Have a status in App.js? Paste it into App.js.
The whole code will be available at the very bottom.
```
import {useState} from "react";
```
The next step is to define the hook in the code. To do this, paste it into the function (above the return).
```
function App () {
const [openMenu, setOpenMenu] = useState (false);
return ();
}
```
What's going on? Let me explain.
openMenu is our variable (same as declaring const, let, var in JavaScript).
setOpenMenu is the function that does all the magic. Its task is to control how our variable openMenu changes, so we will use it to change our state, i.e. openMenu.
For this, we have two braces [] which are nothing more than a destructuring assignment and somehow hide from us what is happening under the hood of that hook.
When it comes to naming, we can name a variable as we want, we call a function by adding the prefix set, i.e. name, setName or data, setData.
useState (false) which is our React hook with the initial value of our state.
To sum up - we have an openMenu that will manage our menu, setOpenMenu will make sure that all state changes are tracked, and the initial value is boolean false because we want to start from a closed menu.
Okay, how do you change the state? Best, in this case, is to write the toggleMobileMenu which we will hook to the button.
```
const toggleMobileMenu = () => {
setOpenMenu (!openMenu);
};
```
What happens inside the function? We use setOpenMenu as packaging. By this, we say to our state, "Hey, what's between the parentheses is your new value, you better keep an eye on it!". OpenMenu is nothing more than a JavaScript shortcut that at the moment says: “openMenu is true? Then give it false! openMenu has false? It will now have true. " This is a classic toggle. I can guarantee you - you will do a lot of toggling during your career!
It's probably high time to write our pseudo-code in React.
App.js
```
import {useState} from "react"; // Import useState
import "./App.css";
function App () {
const [openMenu, setOpenMenu] = useState (false); // We initialize useState with the variable openMenu as false
const toggleMobileMenu = () => {
setOpenMenu (!openMenu);
}; // Function that changes the state from false to true, from true to false
return (
<div className="App">
<button onClick={toggleMobileMenu} class="hamburger-menu">
<span> </span>
<span> </span>
<span> </span>
</button> // Our "hamburger menu"
{openMenu && (
<div className="menu">
<ul>
<li> Home </li>
<li> About </li>
<li> Contact </li>
</ul>
</div> // openMenu && () that is, if openMenu === true, show the menu as false - no
)}
</div>
);
}
export default App;
```
App.css
```
.App {
display: flex;
flex-direction: row-reverse;
justify-content: flex-start;
align-items: flex-start;
margin: 20px;
}
button {
background-color: transparent;
border: 0;
cursor: pointer;
}
.hamburger-menu span {
display: block;
width: 30px;
height: 5px;
margin-bottom: 5px;
background: #cdcdcd;
border-radius: 3px;
}
.hamburger-menu span: first-child {
transform-origin: 0% 0%;
}
.hamburger-menu span: nth-last-child (2) {
transform-origin: 0% 100%;
}
.menu {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
width: 500px;
height: 300px;
background-color: rgb (34, 37, 36);
color: aliceblue;
}
.menu ul li {
text-align: center;
list-style: none;
font-size: 50px;
cursor: pointer;
}
```
It is also worth noting that in our project we can have several states. For example, in the navbar, the state responsible for opening and closing the menu, in App.js, stores information downloaded from the API or switches between the light and dark mode of our website template (popular light / dark theme toggle).
This article did not cover useState, but should shed some light on those new to React. Undoubtedly, these are the basics, and without understanding them it makes no sense to continue learning.
Code available on codepen.