Getting started with useState Hook in React
Unlike class components, functional components do not have a built-in way to store state.
React is a popular JavaScript library used for building user interfaces. It provides developers with a wide range of tools, including Hooks, to make building applications easier and more efficient.
One of the most commonly used Hooks is useState, which allows developers to add state to functional components.
In this article, we will take an in-depth look at useState, its uses, and best practices for its implementation.
What is the useState Hook?#
Before we dive into the specifics of useState, let's first define what Hooks are and how they differ from traditional class components.
A Hook is a function that allows you to use state and other React features in functional components.
Unlike class components, functional components do not have a built-in way to store state. Hooks like useState solve this problem by allowing you to add state to functional components.
Background of the useState Hook#
Before the introduction of the useState Hook in React 16.8, functional components were unable to hold their own state. Instead, developers had to use class components or external state management libraries like Redux to manage state in their applications.
While class components and external state management libraries are still viable options, the introduction of the useState Hook made it much easier for developers to add state to their functional components and simplified the React API overall.
With the useState Hook developers can now use functional components for most use cases, reducing the amount of boilerplate code needed and making it easier to manage state in their applications.
Components of the useState syntax#
The useState Hook takes an initial state value as its argument and returns an array containing two elements: the current state value and a function that updates the state value.
Here is the syntax:
const [state, setState] = useState(initialState);state: The current state value.setState: A function that updates the state value.initialState: The initial value of the state variable that is being declared. This is optional. When no value is provided (not advisable), it's automatically set toundefined.
It's important to note that when you call the update function with a new value, React automatically re-renders your component with that value. If the new value is the same as the current one (compared with Object.is), React skips the re-render.
How to use the useState Hook#
To implement useState, call the function and pass in an initial value as an argument. The function returns an array containing the current state value and a function to update the state.
Here is an example of using useState to manage a simple counter:
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
export default Counter;In this example, we initialize the count state to 0 using the useState Hook. We then render the current count value and a button. When the button is clicked, the count value will be incremented because we added an arrow function with the setCount function.
<button onClick={() => setCount(count + 1)}>Click me</button>When using the useState Hook, it's important to remember to import it from the React library. If you forget, your component fails with ReferenceError: useState is not defined. Here's how to import useState:
import { useState } from 'react';Using different data types with the useState Hook in React#
The useState Hook in React is not limited to managing only string or numeric data types. You can also use it to manage states for different data types, such as arrays, objects, and booleans.
Using arrays with useState Hook#
You can use the useState Hook to manage an array in React. For example, if you have an array of fruits, you can initialize your state with the array:
import { useState } from 'react';
function App() {
const [list, setList] = useState([
{ id: 1, name: 'apple' },
{ id: 2, name: 'banana' },
{ id: 3, name: 'orange' },
]);
const addToList = () => {
const newItem = { id: crypto.randomUUID(), name: 'grape' };
setList([...list, newItem]);
};
return (
<div>
<ul>
{list.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
<button onClick={addToList}>Add Item</button>
</div>
);
}
export default App;In this example, we are using useState to manage an array named list. The initial state of list is set to an array containing three items โ apple, banana, and orange โ each with a unique id.
We also created an addToList function that copies all array items with the spread operator (...) and then adds a new item grape to the list array whenever the "Add Item" button is clicked.
Each item needs a unique id because React uses the key prop to tell list items apart. If you used the fruit name as the key, clicking the button twice would add two items called grape, and React would warn that two children have the same key.
This time, we are not updating the state inline using an arrow function because it's more appropriate to create this operation as a standalone function and call it through the onClick method added to the Add Item button.
Using objects with useState Hook#
You can also use the useState Hook to manage an object in React. Here's an example:
import { useState } from 'react';
function App() {
const [user, setUser] = useState({ name: 'John', age: 30 });
const handleClick = () => {
setUser({ ...user, age: user.age + 1 });
};
return (
<div>
<p>Name: {user.name}</p>
<p>Age: {user.age}</p>
<button onClick={handleClick}>Increase Age</button>
</div>
);
}
export default App;In this example, we are using useState to manage an object named user. The initial state of user is set to an object containing two properties โ name and age.
We also have a function handleClick that copies all object data with the spread operator (...) and also increases the age of the user by 1 whenever the Increase Age button is clicked.
It's important to know that you can assign this object to a variable and then initialize the variable. This is useful when you have a large object or array and would want to write easy-to-understand code:
import { useState } from 'react';
// Declare data
const userData = {
name: 'John',
age: 30,
};
function App() {
const [user, setUser] = useState(userData);
const handleClick = () => {
setUser({ ...user, age: user.age + 1 });
};
return (
<div>
<p>Name: {user.name}</p>
<p>Age: {user.age}</p>
<button onClick={handleClick}>Increase Age</button>
</div>
);
}
export default App;Using booleans with the useState Hook#
You can also use the useState Hook to manage a boolean value in React. Here's an example:
import { useState } from 'react';
function App() {
const [isOn, setIsOn] = useState(false);
const toggleSwitch = () => {
setIsOn(!isOn);
};
return (
<div>
<p>The switch is {isOn ? 'on' : 'off'}</p>
<button onClick={toggleSwitch}>Toggle Switch</button>
</div>
);
}
export default App;In this example, we are using useState to manage a boolean value named isOn. The initial state of isOn is set to false. We also have a function toggleSwitch that toggles the value of isOn whenever the Toggle Switch button is clicked.
This feature can be utilized to manage the toggling of dark and light modes in your projects.
Before we round up, let's explore a more advanced usage of the useState Hook with forms.
The useState Hook and forms#
To handle form data and user input in React, you use state. This is used to keep track of the current values of the form elements. It keeps track of all user interactions, such as typing in a text input or selecting an option from a dropdown, and finally updates the state with the new value.
Here is an example of using useState to create a simple form:
import { useState } from 'react';
const formStateData = {
firstName: '',
lastName: '',
email: '',
};
function Form() {
const [formData, setFormData] = useState(formStateData);
const handleInputChange = (event) => {
const { name, value } = event.target;
setFormData({ ...formData, [name]: value });
};
const handleSubmit = (event) => {
event.preventDefault();
console.log(formData);
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
name="firstName"
value={formData.firstName}
onChange={handleInputChange}
/>
<input
type="text"
name="lastName"
value={formData.lastName}
onChange={handleInputChange}
/>
<input
type="email"
name="email"
value={formData.email}
onChange={handleInputChange}
/>
<button type="submit">Submit</button>
</form>
);
}
export default Form;In this example, we first create an object for the data that will be collected with the form with default values for the firstName, lastName, and email fields. We then initialize the formData state using useState.
const formStateData = {
firstName: '',
lastName: '',
email: '',
};
const [formData, setFormData] = useState(formStateData);We then define a handleInputChange function that updates the formData state whenever a form field is changed.
const handleInputChange = (event) => {
const { name, value } = event.target;
setFormData({ ...formData, [name]: value });
};Finally, we define a handleSubmit function that logs the current form data to the console when the form is submitted.
const handleSubmit = (event) => {
event.preventDefault();
console.log(formData);
};State updates aren't immediate#
One thing that surprises many developers is that calling the update function doesn't change the state variable right away. Each render has its own snapshot of the state, and the new value only shows up in the next render.
function Counter() {
const [count, setCount] = useState(0);
const handleClick = () => {
setCount(count + 1);
console.log(count); // Logs 0, not 1
};
return <button onClick={handleClick}>{count}</button>;
}The same snapshot causes a common bug. If you update the same state twice in one event handler, both calls use the same old value:
const addTwo = () => {
setCount(count + 1);
setCount(count + 1); // count is still 0 here, so the result is 1, not 2
};To update state based on its previous value, pass a function to the update function instead. React calls it with the latest state:
const addTwo = () => {
setCount((prevCount) => prevCount + 1);
setCount((prevCount) => prevCount + 1); // The result is 2
};This is called a functional update. Use it whenever the new state depends on the old one, such as incrementing a counter, toggling a boolean, or adding an item to an array.
useState best practices#
When using the useState Hook, following a few best practices helps you avoid common bugs and unnecessary work:
- Use functional updates: When the new state depends on the previous state, pass a function, as in
setCount((prev) => prev + 1), as shown in the previous section. - Don't mutate state: Always create a new array or object instead of changing the existing one. If you call
list.push(item)and thensetList(list), React sees the same array and skips the re-render. Use the spread operator or methods that return a new array, likemapandfilter. - Keep state flat and focused: Instead of storing everything in one deeply nested object, split unrelated values into separate
useStatecalls. This makes updates simpler. - Don't store values you can calculate: If a value can be computed from props or other state, such as a full name from a first and last name, calculate it during rendering instead of keeping it in state.
- Initialize expensive state lazily: If calculating the initial value is expensive, pass the function itself, as in
useState(createInitialItems), not its result, as inuseState(createInitialItems()). React then calls it only on the first render instead of on every render. - Don't use effects to batch updates: Since React 18, React automatically batches multiple state updates from the same event into a single re-render, so you don't need extra code for it. Using the
useEffectHook to set state that depends on other state actually adds an extra render. - Avoid unnecessary re-renders of child components: When a component's state changes, React re-renders it and all of its children. If a child component is expensive to render and its props haven't changed, wrap it in
memo, as inconst List = memo(function List({ items }) { ... }), so React can skip it. Measure before you optimize, though, and note that if your project uses the React Compiler, it applies this kind of memoization for you.
Summary#
In this article, we explored the useState Hook in depth and learned how to use it to add state to functional components. We also discussed how to use useState with arrays, objects, booleans, and forms, why state updates aren't immediate, and covered best practices for avoiding common bugs. By following these best practices, you can ensure that your React applications are efficient, scalable, and easy to maintain.
Looking for the ideal hosting solution for your React applications? You can deploy them for free with Sevalla's Static Site Hosting, or use Application Hosting if your app needs a server.