The React useState
Hook allows us to track state in a function component.
State generally refers to data or properties that need to be tracking in an application.
we need to Import useState
To use the useState
Hook, we first need to import
it into our component.
import { useState } from "react";
Initialize useState
We initialize our state by calling useState
in our function component.
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 GetColor() {
const [color, setColor] = useState("");
}
we can notice here, we are de structuring the returned values from useState
.
The first value, color
, is our current state.
The second value, setColor
, is the function that is used to update our state.
we set the initial state to an empty string: useState("")
nice post
ReplyDeletegood post and example
ReplyDelete