What is useState() in React?

Web Development

In this React tutorial I will explain what useState() is and how to use the useState( ) hook in React js by giving a example.

Table of content:

  1. What is useState
  2. How to install react
  3. Example using vanilla JavaScript
  4. Prevent default behavior of forms
  5. How to use variables in React
  6. How to use functions in React
  7. Using events in react
  8. Change the value of a variable using regular javascript in react
  9. How to import useState in react
  10. How to use useState in React How to change state in React

1. What is useState

The useState() is a React Hook that allows you to have state variables in functional components. In other words, useState() is the ability to encapsulate local information in a functional component.

2. How to install react

Create React App

Create React App is the best way to building a new single-page application in React.

It sets up your development environment so that you can use the latest JavaScript features, and optimizes your app for production. You’ll need to have Node >= 14.0.0 and npm >= 5.6 on your machine. To create a project, run:

npx create-react-app my-app
cd my-app
npm start

3. Example using vanilla JavaScript

First let’s give a example using regular javascript in order to understand where things are coming from.

Now let’s get started by cleaning up our newly created application and leaving only the necessary for our explanation. Next delete everything from your return in your App() and replace it with a simple title like shown below.

import "./App.css";

function App() {
  return (
    <div className="App">
      <h1>useState</h1>
     
    </div>
  );
}

4. Prevent default behavior of forms

Now add content to your return by adding a h2 and a form which will contain a input tag that is meant to contain the content for our changeable data.

In order to submit the information from our form you need to add `button type=”submit”`, by clicking on the button the information from the input tag will be submitted.

The problem is that the form is trying to send the information to a backend that we dont have so you will have to stop its default behavior by using the `preventDefault()`.

return (
    <div className="App">
      <h1>useState</h1>
     <h2>Name</h2>
      <form onSubmit={(e) => e.preventDefault()}>
        <input type="text"  />
         <button type="submit">
          change name
        </button> 
      </form>
    </div>
  );

5. How to use variables in React

In order to change the content of the h2 you can replace the text with a variable.

Create a variable using the let keyword and name it name. After having the variable initialized you can now assign a value to it in form of a string.

 let name;
  name = "Norbert";

In order to use the variable in your app, you need to add it using { } in your return. Now in stad of the text Name the value of the variable `name` will appear.

return (
    <div className="App">
      <h1>useState</h1>
 
       <h2>{name}</h2> 

      <form onSubmit={(e) => e.preventDefault()}>
        <input type="text"  />
         <button type="submit">
          change name
        </button> 
      </form>
    </div>
  );

6. How to use functions in React

In React functions are declared before the return of the component. In order to initialize a function you can do so before the return and also in the return. In our case you will use it in the return because it will be called upone by a event.

import "./App.css";

function App() {
  // JavaScript
  let name;
  name = "Norbert";

  function executeChange() {
// execut 
  }

  return (
    <div className="App">
      <h1>useState</h1>
    
     <h2>{name}</h2> 

      <form onSubmit={(e) => e.preventDefault()}>
        <input type="text"  />
        <button type="submit" >
          change name
        </button>
      </form>
    </div>
  );
}

7. Using events in react

In order to execute the function you need a eventlistener, in this case because the element we are targeting is a button we will edd to it the event of Click. This is done in react using the onClick event and assigning it to its event handler.

return (
    <div className="App">
      <h1>useState</h1> 
      <h2>{name}</h2>
      <form onSubmit={(e) => e.preventDefault()}>
        <input type="text" />

     <button type="submit" onClick={executeChange}>
          change name
        </button>


      </form>
    </div>

In order to test if the event is calling the function you can add a console.log(“test “) in the function.


  function executeChange() {
    // console.log("test");
 
  }

Now open up the console in the browser and click the button.

8. Change the value of a variable using regular javascript in react

You can now change the value of the variable by targeting the information that is passt in the input tag by targeting the e.target.value.

function executeChange() {
    const input = document.querySelector("input");

    // console.log(input.value);
    const newName = input.value;
    name = newName;
    console.log(name);
    document.querySelector("h2").innerHTML = name;
    return name;
  }

Get the input tag from the DOM and reassign the new value to the name variable.

9. How to import useState in react

In order to use the React useState() hook, first you need to import it from the react library. Simply import the the hook like ths.

import { useState } from "react";

Don’t forget to import it using { } because it is actually a function.

useState Syntax:

The first element is the initial state and the second one is a function that is used for updating the state.

const [state, setState] = useState(initialstate)

The useState hook is a special function that takes the initial state as an argument and returns an array of two entries. UseState encapsulate only singular value from the state, for multiple state need to have useState calls.

10. How to use useState() in React How to change state in React

Now for the moment of truth. useState to create a newName variable and a function that will update that variable upon a state change handler.

You can also pass int values in the state which then will be asingt to the state.

const [newName, setNewName] = useState("NorbertBM");

Next create the handler for changing the state.

const handelChangeName = (e) => {
    // console.log(e.target.value);
    // setNewName("Laura");

    setNewName(e.target.value);
  };

This is simpli a arrow function that executes when it is triggered. The Trigger will be a on cahnge event in the input tag.

<input type="text" onChange={handelChangeName} />

For more information check out the video tutorial on YouTube.


Want to become a web developer ?

Love Podcast about web development?

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.