The useState
Hook in React enables state management within function components. State usually represents data or properties that an application needs to track.
Importing useState
To incorporate the useState
Hook, you must import it into your component.
Example
At the beginning of your component, import the useState
Hook:
import { useState } from "react";
Notice that we use destructuring to import useState
from React as it is a named export.
Initializing State with useState
To initiate state, invoke useState
within your function component.
useState
takes an initial state value and returns a pair of values:
- The current state.
- A function to update the state.
Example
Set up state initialization at the top of the function component:
import { useState } from "react"; function FavoriteFruit() { const [fruit, setFruit] = useState(""); }
Once again, we destructure the values returned by useState
.
- The first value,
fruit
, is the current state. - The second value,
setFruit
, is the function to update the state.
These variable names can be customized to your liking.
Finally, we initialize the state with an empty string: useState("")
.
Reading State
We can now use our state anywhere in our component.
Example
Utilize the state variable within the rendered component:
import { useState } from "react"; import ReactDOM from "react-dom/client"; function FavoriteFruit() { const [fruit, setFruit] = useState("banana"); return <h1>My favorite fruit is {fruit}!</h1>; } const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<FavoriteFruit />);
Updating State
To update the state, employ the state updater function.
Directly modifying the state, e.g., fruit = "banana"
, is not allowed.
Example
Use a button to change the state:
import { useState } from "react"; import ReactDOM from "react-dom/client"; function FavoriteFruit() { const [fruit, setFruit] = useState("banana"); return ( <> <h1>My favorite fruit is {fruit}!</h1> <button type="button" onClick={() => setFruit("apple")} >Apple</button> </> ); } const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<FavoriteFruit />);
What Can State Hold?
The useState
Hook can manage strings, numbers, booleans, arrays, objects, and combinations of these!
You can create multiple state Hooks for individual values.
Example
Create multiple state Hooks:
import { useState } from "react"; import ReactDOM from "react-dom/client"; function Vehicle() { const [make, setMake] = useState("Toyota"); const [model, setModel] = useState("Corolla"); const [year, setYear] = useState("2005"); const [color, setColor] = useState("blue"); return ( <> <h1>My {make}</h1> <p> It is a {color} {model} from {year}. </p> </> ); } const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<Vehicle />);
Alternatively, you can use one state Hook to hold an object!
Example
Use a single Hook to maintain an object:
import { useState } from "react"; import ReactDOM from "react-dom/client"; function Vehicle() { const [vehicle, setVehicle] = useState({ make: "Toyota", model: "Corolla", year: "2005", color: "blue" }); return ( <> <h1>My {vehicle.make}</h1> <p> It is a {vehicle.color} {vehicle.model} from {vehicle.year}. </p> </> ); } const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<Vehicle />);
Since we’re now tracking a single object, reference the object and its properties when rendering the component (e.g., vehicle.make
).
Updating Objects and Arrays in State
When state is updated, the entire state is overwritten. What if we only want to modify the color of our vehicle?
Calling setVehicle({color: "green"})
would remove the make, model, and year from our state. We can use the JavaScript spread operator to help us.
Example
Utilize the spread operator to update only the color:
import { useState } from "react"; import ReactDOM from "react-dom/client"; function Vehicle() { const [vehicle, setVehicle] = useState({ make: "Toyota", model: "Corolla", year: "2005", color: "blue" }); const changeColor = () => { setVehicle(previousState => { return { ...previousState, color: "green" }; }); }; return ( <> <h1>My {vehicle.make}</h1> <p> It is a {vehicle.color} {vehicle.model} from {vehicle.year}. </p> <button type="button" onClick={changeColor} >Green</button> </> ); } const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<Vehicle />);