How to Use useState Hook in ReactJS – with Examples

How to Use useState() Hook in ReactJS with Examples

If you are new in the React world or have some experience working on it, you must know what is useState() hook is.

React provides several hooks that help developers add, remove, or change items in a list, toggle modals, and fetch data. By using hooks such as useState(), you can create more advanced components that can handle user interactions and dynamic changes.

In this article, we will guide you on how to use useState() hook. As well as we are providing 4 different examples so you will have an in-depth understanding of what is useState() hook is and how to use it effectively.

What is useState()?

In ReactJS, the useState() hook is a built-in function that is used to make components more dynamic and complex. Without hooks, components may only have static data or simple lists. However, as the application becomes more complex, hooks become necessary to complete various tasks.

The useState() is a built-in hook function in ReactJS that allows functional components to have state variables. It provides a way to manage state in functional components, which before was only possible with class components using this.state and this.setState().

useState() returns an array with two elements – the current state value and a function that updates the state value. Below is a simple example to create useState() hook with the initial text “Hello World”:

const [text, setText] = useState("Hello World");

In the above example, text is the current state value, and setText is the function that you can use to update the state. When the page first loads, the value of the text will be “Hello World” since that is the initial value passed to useState().

React will re-render the component whenever it updates the state, and the UI will reflect the new state.

To help you understand how to use the useState() hook in React, we will go through some easy examples:

  1. Change the text “Hello World” using useState() with a toggle button
  2. Display an array using useState()
  3. Display an object using useState()
  4. Create a simple Counter example using useState()

By exploring these examples, we’ll be able to see firsthand how the useState() hook works and how it can be used to make our components more dynamic and interactive. These examples will also provide a foundation for building more complex applications with React.

To try out the examples of using the useState() hook in React, you’ll need to create a new React app. You can follow the instructions in the How to Create Your First ReactJS App: Hello World Example article to create the app.

Let’s dive into these examples to see how to use the useState() hook in React.

Example 1: Change the text “Hello World” using useState() with a toggle button

In this example, we will create a button and a heading tag using HTML. When the button labeled “Change Text” is clicked, the text displayed on the heading tag will switch back and forth between “Hello World” and “Welcome to React”.

To implement this, simply copy and paste the following source code into the src/index.js file.

import React, { useState } from "react";
import { createRoot } from "react-dom/client";

function HelloWorld() {
  const [text, setText] = useState("Hello World");

  const handleClick = () => {
    if (text == "Hello World") {
      setText("Welcome to React");
    } else {
      setText("Hello World");
    }
  };

  return (
    <React.Fragment>
      <h1>{text}</h1>
      <button type="button" onClick={handleClick}>
        Change Text
      </button>
    </React.Fragment>
  );
}

const root = createRoot(document.getElementById("root"));
root.render(<HelloWorld />);

The code above has a function called handleClick(). It checks if the text is “Hello World” and if it is, it calls setText() with “Welcome to React” as the argument. Otherwise, it calls setText() with “Hello World”.

To see the result of this code, run the React app using npm start and go to http://localhost:3000/ in your web browser. The output should look like the screenshot below.

display-text-react

Example 2: Display an array using useState()

If we have an array of colors that we want to display on an HTML page and as well as add a button to remove a specific color.

To achieve this, we can use the following code in our src/index.js file, which will display all colors from the array and create a button to remove them.

import React, { useState } from "react";
import { createRoot } from "react-dom/client";

import "./index.css";

function ShowColors() {
  const data = [
    { id: 1, color: "Red" },
    { id: 2, color: "Green" },
    { id: 3, color: "Blue" },
    { id: 4, color: "Yellow" },
  ];

  const [colors, setColor] = useState(data);

  const removeItem = (id) => {
    let newColor = colors.filter((item) => item.id !== id);
    setColor(newColor);
  };

  return (
    <React.Fragment>
      <section className="container">
        {colors.map((item) => {
          const { id, color } = item;

          return (
            <div key={id} className="item">
              <h4>{color}</h4>
              <button className="btn" onClick={() => removeItem(id)}>
                Remove
              </button>
            </div>
          );
        })}
        <button className="btn" onClick={() => setColor([])}>
          Clear Items
        </button>
      </section>
    </React.Fragment>
  );
}

const root = createRoot(document.getElementById("root"));
root.render(<ShowColors />);

To add styling to our web page, we need to create a new file in the src folder called index.css. This file will contain all the required styles to make our page user-friendly. Simply copy the code below and paste it into the newly created src/index.css file.

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.container {
  width: 200px;
  margin: 2rem;
}

.item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
}

.btn {
  display: inline-block;
  background: hsl(205, 78%, 60%);
  color: #fff;
  padding: 0.25rem 0.75rem;
  border-radius: 0.25rem;
  border-color: transparent;
  cursor: pointer;
  transition: all 0.3s linear;
}

.btn:hover {
  background: hsl(205, 86%, 17%);
  color: hsl(205, 78%, 60%);
}

After making the necessary changes, save the file and start the React app. The web page will display all the colors from the array along with a “Remove” button for each color. Clicking on the “Remove” button will delete the corresponding color.

Additionally, there is a “Clear Items” button that can be used to delete all the colors from the list. The final web page will look like the screenshot given below.

Example 3: Display an object using useState()

Let’s explore how to display an object in React using the useState() hook. Accessing object members is similar to accessing any variable, as seen in example 1. We simply use the object name to access its members.

In this example, we have an object with three members. We want to display the object data and change the message member with useState() when a button is clicked.

Copy the below code and paste it into the src/index.js file to implement the solution to the above problem.

import React, { useState } from "react";
import { createRoot } from "react-dom/client";

function ObjectExample() {
  const [person, setPerson] = useState({
    name: "Vilash Daate",
    age: 31,
    message: "How are you?",
  });

  const changeMessage = () => {
    setPerson({ ...person, message: "I am fine" });
  };

  return (
    <React.Fragment>
      <h3>{person.name}</h3>
      <h3>{person.age}</h3>
      <h3>{person.message}</h3>

      <button onClick={changeMessage}>Change Message</button>
    </React.Fragment>
  );
}

const root = createRoot(document.getElementById("root"));
root.render(<ObjectExample />);

When you run the code in the browser, you will see the message “How are you?” displayed on the screen. When you click the “Change Message” button, the message will change to “I am fine”.

display-object-react

Example 4: Create a simple Counter example using useState()

Let’s create a simple counter app in React. It will have three buttons: Increase, Decrease, and Reset, which will respectively increment, decrement, or reset the counter. The useState() hook will be used to update and render the counter value.

To implement this, copy and paste the following code into your src/index.js file.

import React, { useState } from "react";
import { createRoot } from "react-dom/client";

function CounterExample() {
  const [value, setValue] = useState(0);

  return (
    <React.Fragment>
      <h1>{value}</h1>

      <button onClick={() => setValue(value - 1)}>Decrease</button>
      <button onClick={() => setValue(0)}>Reset</button>
      <button onClick={() => setValue(value + 1)}>Increase</button>
    </React.Fragment>
  );
}

const root = createRoot(document.getElementById("root"));
root.render(<CounterExample />);

After running the React app, you will see a result like the below screenshot. You can try increasing, decreasing, and resetting the value by clicking on the corresponding buttons.

counter-example-react

Conclusion

The useState() hook in React JS is a powerful tool that allows functional components to have state variables, making them more dynamic and interactive. By exploring the examples provided, developers can see how the useState() hook works and how it can be used to create more advanced components. Overall, hooks are essential for handling user interactions and dynamic changes in more complex applications with React.

Related: See our guide on Top 6 Essential Rules for Writing JSX in React JS for more details.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top