[React.js] - Part 10. React Hooks - useState Hook

Ace Lennox
The useState
Hook is a fundamental part of React, empowering developers to manage state within functional components. This guide will walk you through everything you need to know about useState
, from basic usage to handling more complex scenarios.
What is useState
?
In React, state refers to data that a component tracks and updates dynamically. The useState
Hook lets you manage this state in a clean and efficient way, without needing to use class components.
How to Use useState
Importing useState
To use the useState
Hook, you must first import it. Since it’s a named export, you can include it like this:
import { useState } from "react";
Initializing State
When you call useState
, you provide an initial value. This function returns an array with two elements:
The current state.
A function to update the state.
Here’s an example:
function FavoriteFood() {
const [food, setFood] = useState("pizza");
}
In this example:
food
holds the current state.setFood
is the function used to update the state.
Reading State
You can access and display the current state anywhere in your component:
<h1>My favorite food is {food}!</h1>
React ensures that the UI re-renders whenever the state changes.
Updating State
To update state, call the updater function (setFood
in our example). It’s important not to modify the state directly (e.g., food = "sushi"
), as React won’t detect these changes.
Example:
function FavoriteFood() {
const [food, setFood] = useState("pizza");
return (
<>
<h1>My favorite food is {food}!</h1>
<button onClick={() => setFood("sushi")}>Change to Sushi</button>
</>
);
}
Handling Complex State
The useState
Hook can manage various data types, including objects and arrays. Here’s how to use it with more complex data structures.
Using Objects
Consider managing the state of a car:
function Vehicle() {
const [car, setCar] = useState({
brand: "Toyota",
model: "Corolla",
color: "white",
year: 2022
});
return (
<>
<h1>My {car.brand}</h1>
<p>It is a {car.color} {car.model} from {car.year}.</p>
</>
);
}
Updating Object Properties
To update specific properties in an object, use the JavaScript spread operator (...
) to retain other values:
function Vehicle() {
const [car, setCar] = useState({
brand: "Toyota",
model: "Corolla",
color: "white",
year: 2022
});
const updateColor = () => {
setCar((prevState) => ({
...prevState,
color: "blue"
}));
};
return (
<>
<h1>My {car.brand}</h1>
<p>It is a {car.color} {car.model} from {car.year}.</p>
<button onClick={updateColor}>Change Color</button>
</>
);
}
Why Use the Spread Operator?
The spread operator copies all properties from the existing state, ensuring that only the intended property (color
) is updated.
Best Practices
Choose meaningful initial values: This improves code readability and avoids unnecessary checks.
Never mutate state directly: Always use the updater function.
Group related data: Use a single object state to keep related properties together.
Leverage functional updates: When state updates depend on the previous state, use the functional form of the updater function.
Wrapping Up
The useState
Hook is a powerful tool that simplifies state management in functional components. Whether you’re handling a simple string or a complex object, understanding useState
unlocks the ability to build dynamic and interactive applications in React.
Experiment with the examples above and watch your React components come to life!
Source Code
The complete source code for this part is available on GitHub