The React useState Hook enables us to manage state within a functional component.
State typically refers to data or properties that need to be monitored and updated within an application.
To utilize the useState Hook, we must first import it into our component.
import { useState } from “react”; |
Note that we are destructuring useState
from React, as it is a named export.
For more information on destructuring, take a look at the ES6 section. |
We initialize state in our functional component by calling useState, which takes an initial state and returns the current state along with a function to update it.
Set up the state at the beginning of the function component.
import |
Again, note that we are destructuring the values returned by useState.
The first value, color, represents the current state, while the second value, setColor, is the function used to update the state.
These names are variables that can be customized to whatever you prefer. |
Finally, we set the initial state to an empty string with useState(“”).