React Basics - State and useState

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.

Content

Got a project?

Let's talk!

__wf_zastrzeżone_dziedziczyć
Technologies
What is AWS?
arrow icon
4.1.2024
2 min read
Technologies
Technologies
HTML - co to?
arrow icon
3.20.2024
2 min czytania
Technologies
What is HTML?
arrow icon
3.21.2024
2 min read
Technologies
Technologies
TypeScript? - co to?
arrow icon
3.20.2024
3 min czytania
Technologies
What is TypeScript?
arrow icon
3.20.2024
3 min read
Technologies
Technologies
PHP - co to?
arrow icon
3.19.2024
1 min czytania
Technologies
What is PHP?
arrow icon
3.19.2024
1 min read
Technologies
Technologies
Swift - co to?
arrow icon
3.18.2024
5 min czytania
Technologies
What is Swift?
arrow icon
3.18.2024
5 min read
Technologies
Technologies
Kotlin - co to?
arrow icon
3.16.2024
4 min czytania
Technologies
What is Kotlin?
arrow icon
3.16.2024
4 min read
Technologies
Technologies
Vue.js - co to?
arrow icon
3.15.2024
3 min czytania
Technologies
Technologies
What is Vue.js?
arrow icon
3.15.2024
3 min read
Technologies
Technologies
JAVA - Co to?
arrow icon
3.14.2024
4 min czytania
Technologies
What is JAVA?
arrow icon
3.13.2024
2 min read
Technologies
Technologies
React Native - co to?
arrow icon
3.13.2024
3 min czytania
Technologies
What is React Native?
arrow icon
3.13.2024
3 min read
Technologies
Technologies
React.js - co to?
arrow icon
3.13.2024
2 min czytania
Technologies
What is React.js?
arrow icon
3.13.2024
2 min read
Technologies
Node.js - co to?
arrow icon
3.13.2024
1 min czytania
Technologies
What is Node.js?
arrow icon
3.13.2024
1 min read
Technologies
Technologies
JavaScript - co to?
arrow icon
3.13.2024
1 min czytania
Technologies
What is JavaScript?
arrow icon
3.13.2024
1 min read
Knowledge hub
Knowledge hub
Kim jest fullstack developer?
arrow icon
3.13.2024
1 min czytania
Knowledge hub
What is a fullstack developer?
arrow icon
3.13.2024
1 min read
Knowledge hub
Knowledge hub
Co to jest frontend?
arrow icon
3.13.2024
2 min czytania
Knowledge hub
What is frontend?
arrow icon
3.13.2024
2 min read
Knowledge hub
Knowledge hub
Co to jest backend?
arrow icon
3.13.2024
2 min czytania
Knowledge hub
What is backend?
arrow icon
3.13.2024
2 min read
Business
Business
Profesjonalna aplikacja dla firmy - 10 wskazówek
arrow icon
5.12.2023
7 min czytania
Business
Business
Doradztwo IT - korzyści dla Twojej firmy
arrow icon
3.21.2023
6 mi czytania
IT
How to get started in IT?
arrow icon
3.6.2023
7 min read
IT
WEB3 - What is it? Introduction
arrow icon
2.21.2023
4 min read
Code
Code
Czy MobX to dobra alternatywa dla Redux?
arrow icon
2.1.2023
3 min czytania
UX/UI
UX/UI
UX Design - przewodnik dla programistów
arrow icon
1.30.2023
4 min czytania
Code
Code
Podstawy React’a - stan i hook useState
arrow icon
1.26.2023
5 min czytania
Startup
Startup
Startup - z jaką firmą IT współpracować?
arrow icon
12.20.2022
11 min czytania
Business
Business
Najlepszy kraj do outsourcingu IT
arrow icon
12.12.2022
4 min czytania
Business
Business
Jak zmienić firmę programistyczną?
arrow icon
12.2.2022
4 min czytania
Business
Business
Outsourcing IT- kompletny PRZEWODNIK!
arrow icon
11.28.2022
3 min czytania
Business
Business
Team Augmentation - Korzyści!
arrow icon
11.23.2022
9 min czytania
Business
Business
W co inwestować pieniądze w 2021 roku?
arrow icon
11.21.2022
3 min czytania
Business
Business
Praca w różnych strefach czasowych. Jak to działa?
arrow icon
11.18.2022
7 min czytania
Startup
Startup
Co to jest startup? (Nowoczesne Przedsiębiorstwo)
arrow icon
11.17.2022
6 min czytania
Business
Business
Co to jest outsourcing pracowników IT i ILE kosztuje
arrow icon
11.14.2022
5 min czytania