React useState hook

React useState hook

Introduction

the useState hook is one of the most commonly used hooks in React, it simplifies state management in functional components, leading to cleaner, more maintainable code and improved developer productivity.

Why and when should we need to use this hook?

We use useState hook So we could handle changeable data that can affect the UI. This will help when you're building your project using React and Typescript, since if you store the variables in Typescript, you won't be able to see the changes in the UI even if the value of the variable has changed.

How to use the useState hook

  • First, you need to import the hook from React:

      "use client";
    
      import { useState } from "react";
    

    adding "use client" since this hook is used on the client side

  • In a function you've created, call the useState hook like this:

      const [age, setAge] = useState(0);
    

    the age will be the variable, and setAge is the function that will be used to change the value of the variable. the 0 in useState(0) is the initial value for the variable.

  • now to update the changes on the variable, we need to create another function using setAge to implement the changes on the variable. for example:

      const increaseAge = () => {
          setAge(age + 1);
        };
    
  • To show the final result of our work, we need to recall the function we've created. So for example, here is a simple code where you can increase or decrease your age. This is the code:

      "use client";
    
      import { useState } from "react";
    
      export default function Age() {
        const [age, setAge] = useState(0);
    
        const IncreaseAge = () => {
          setAge(age + 1);
        };
    
        const DecreaseAge = () => {
          setAge ( age - 1)
        }
    
        return (
          <div className="flex flex_row m-20">
            <button className="btn btn-primary" onClick={DecreaseAge}>Decrease Age</button>
            <div className="bg-white w-20 text-black font-bold text-center">{age}</div>
            <button className="btn btn-primary" onClick={IncreaseAge}>Increase Age</button> <br />
            <input type="text" />
          </div>
        );
      }
    

    Here is the result:

    Here you can see that the counter started at the initial value 0 and then it changed depending on how many times you pressed the button.

Using the functions in useState

There are two ways to recall the function that you've created to change the value of the variable. the first one is the same as the last example, where you recall the name of the function in an onClick event in the button. But sometimes, especially if the function uses a simple logic, you can immediately use the function logic inside the event. For example:

<button class="btn btn-secondary" onClick={() => {setAge(age - 1)}}>Decrease Age</button>

Since the event will only point to the function and it's not a function itself, for example, if we had a product with the initial value of $10, the value of the product will change depending on what option you choose. The code is

"use client";

import { useState } from "react";

export default function Price() {
  const [price, setPrice] = useState(0);
  const productPrice = 10;

  const handlePriceButton = (x: number) => {
    setPrice(productPrice + x);
  };

  return (
    <div className="card w-96 shadow-xl bg-white text-black m-20">
      <div className="card-body items-center text-center">
        <p className="text-center">Coffee: ${price}</p>
        <div className="card-actions">
          <button
            className="btn btn-primary"
            onClick={() => handlePriceButton(0.5)}
          >
            Small
          </button>
          <button
            className="btn btn-primary"
            onClick={() => handlePriceButton(2.5)}
          >
            Medium
          </button>
          <button
            className="btn btn-primary"
            onClick={() => handlePriceButton(4)}
          >
            Large
          </button>
        </div>
      </div>
    </div>
  );
}

The result will be:

Conclusion

The past examples were only simple examples of how to use the useState and it doesn't show the full use of this hook.

In the end, the useState hook is a viable tool for React development. Whether you're building a small application or a large-scale project, useState hook can greatly improve your development experience and the quality of your code because of its simplicity, predictability, performance benefits, and compatibility with modern React practices.