You will learn about the state in React when you start working with it. The state is one of the most important concepts to learn. It allows components to be dynamic, interactive and able to respond to user actions.
You will learn about the state, what it is for and how to use it correctly in this tutorial.
The state is an object that stores information which can change during a component’s lifetime. Every time the state changes, React re-renders the component to display the new data on the interface.
Think of the state as a component’s internal memory. It serves to store data that may be modified over time, such as:
Before continuing, it is essential to understand the difference between props and state.
The props are data that a component receives from its parent component. They are immutable, meaning the component should not modify them.
The state, on the other hand, is internal to the component and can be modified. It is managed by the component itself.
In modern React, the state is typically managed using the useState hook. This hook allows adding state to functional components.
To use it, you need to import it from React:
import { useState } from "react";
You can then create a state inside the component:
function Counter() { const [counter, setCounter] = useState(0); return ( Current value: {counter} ); }
How stateWorks
The function stateUse returns an array with two elements:
We have an example in the previous section:
Every time you call setContador, React will re-render the component with the new value.
The state should never be modified directly. This is incorrect:
counter = counter + 1;
You should always use the update function:
setCounter(counter + 1);
You can also update the state using a function, which is recommended when the new value depends on the previous one:
setCounter(prev => prev + 1);
Using multiple states in a component
You can declare as many states as you need within the same component.
function User() { const [name, setName] = useState(""); const [age, setAge] = useState(0); return ( setName(e.target.value)} /> setAge(Number(e.target.value))} /> {name} is {age} years old ); }
States with objects
The state can also store objects or arrays. In these cases, it’s essential to create a copy of the object when updating it.
const [user, setUser] = useState({ name: "", age: 0 });
Updating the state correctly:
setUser({ ...user, name: "Ismael" });
The spread operator allows you to copy the previous state before modifying a property.
You should use state when the data:
If a data does not change or does not affect the rendering, it usually doesn’t need to be in the state.
