
REACT USESTATE HOOK:
- 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.
Import useState:
To use the useState Hook, we first need to import it into our component.
import { useState } from "react";
Intialize the 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:
import { useState } from "react";
function FavoriteColor() {
const [color, setColor] = useState("");
}
- The first value, color, is our current state.
- The second value, ,setColor is the function that is used to update our state.
- Lastly, we set the initial state to an empty string:
useState("")
Read State:
Example:
import { useState } from "react";
import ReactDOM from "react-dom/client";
function FavoriteColor() {
const [color, setColor] = useState("red");
return <h1>My favorite color is {color}!</h1>
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<FavoriteColor />);
Output: My favorite color is red!
Update State:
- To update our state, we use our state updater function.
Example:
import { useState } from "react";
import ReactDOM from "react-dom/client";
function FavoriteColor() {
const [color, setColor] = useState("red");
return (
<>
<h1>My favorite color is {color}!</h1>
<button
type="button"
onClick={() => setColor("blue")}
>Blue</button>
</>
)
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<FavoriteColor />);
Output: My favorite color is red!