React useState Hook


React in useState Hook allows us to track the status of the operating component.

State usually refers to data or features that need to be tracked in an application.


Import useState

To use the useState Hook, we first need to import it on our site.


Example

At the top of your component, import the useState Hook

import { useState } from "react";
        

Note that we are destroying the useState from react as it is called exporting.


Initialize useState

We begin our situation by calling the useState in our service section.

useState accepts an initial state and returns two values:

  • The current state.
  • A function that updates the state.

Example

Initialize state at the top of the function component.

import { useState } from "react";

            function FavoriteColor() {
              const [color, setColor] = useState("");
            }
            

Note, too, that we are demolishing returned values ​​in the useState.

First value, color, our current status.

The second value, setColor, is a function used to update our status.


These are just some of the goal setting shareware that you can use.


Lastly, we set the status quo for the empty series: you are in useState("")


Read State

Now we can put our status anywhere on our part


Example

Use the state variable in the rendered component.

import { useState } from "react";
            import ReactDOM from "react-dom";
            
            function FavoriteColor() {
              const [color, setColor] = useState("red");
            
              return <h1>My favorite color is {color}!</h1>
            }
            
ReactDOM.render(<FavoriteColor />, document.getElementById('root'));
            


Update State

In order to update our status, we use our status update function.


We should never review the situation directly. Example: color = "red" is not allowed.


Example

Use a button to update the state:

import { useState } from "react";
            import ReactDOM from "react-dom";
            
            function FavoriteColor() {
              const [color, setColor] = useState("red");
            
              return (
                <>
                  <h1>My favorite color is {color}!</h1>
                  <button
                    type="button"
                    onClick={() => setColor("blue")}
                  >Blue</button>
                </>
              )
            }
            
ReactDOM.render(<FavoriteColor />, document.getElementById('root'));
            


What Can State Hold

The useState State Hook can be used to track cables, numbers, booleans, arrays, objects, and any combination of these!

We can create multiple Hooks to track individual values.


Example

Create multiple state Hooks:

import { useState } from "react";
            import ReactDOM from "react-dom";
            
            function Car() {
              const [brand, setBrand] = useState("Ford");
              const [model, setModel] = useState("Mustang");
              const [year, setYear] = useState("1964");
              const [color, setColor] = useState("red");
            
              return (
                <>
                  <h1>My {brand}</h1>
                  <p>
                    It is a {color} {model} from {year}.
                  </p>
                </>
              )
            }
            
ReactDOM.render(<Car />, document.getElementById('root'));
            

Or, we can just use one circuit and replace it with something!


Example

Create a singe Hook that holds an object:

import { useState } from "react";
            import ReactDOM from "react-dom";
            
            function Car() {
              const [car, setCar] = useState({
                brand: "Ford",
                model: "Mustang",
                year: "1964",
                color: "red"
              });
            
              return (
                <>
                  <h1>My {car.brand}</h1>
                  <p>
                    It is a {car.color} {car.model} from {car.year}.
                  </p>
                </>
              )
            }
            
ReactDOM.render(<Car />, document.getElementById('root'));
            

Since we are now tracking one item, we need to refer to that item and the property of that item when we deliver the part. (Example: car.brand)



Updating Objects and Arrays in State

When status is reviewed, the entire region is overwritten.

What if we only wanted to update the color of our car?

If we only call setCar({color: "blue"}), this will remove the type, model, and year from our state.

We may use JavaScript operators to help us.


Example

Use the JavaScript spread operator to update only the color of the car:

import { useState } from "react";
            import ReactDOM from "react-dom";
            
            function Car() {
              const [car, setCar] = useState({
                brand: "Ford",
                model: "Mustang",
                year: "1964",
                color: "red"
              });
            
              const updateColor = () => {
                setCar(previousState => {
                  return { ...previousState, color: "blue" }
                });
              }
            
              return (
                <>
                  <h1>My {car.brand}</h1>
                  <p>
                    It is a {car.color} {car.model} from {car.year}.
                  </p>
                  <button
                    type="button"
                    onClick={updateColor}
                  >Blue</button>
                </>
              )
            }
            
ReactDOM.render(<Car />, document.getElementById('root'));
            

Because we need the current state of the status, we transfer the function to our setCar function. This function receives the previous value.

Then we return the item, distribute the previousState and write over color only.