Using multiple state variables lets you keep track of different pieces of information separately in your component. This makes your code clearer and easier to manage.
0
0
Multiple state variables in React
Introduction
You want to track a user's name and age separately in a form.
You need to toggle a menu open or closed and also count how many times it was opened.
You want to store a list of items and also keep track of which item is selected.
You have a counter and a text input that change independently.
Syntax
React
const [state1, setState1] = useState(initialValue1); const [state2, setState2] = useState(initialValue2);
Each state variable has its own setter function to update it.
Use separate state variables for unrelated data to keep things simple.
Examples
One state for a number, one for a text string.
React
const [count, setCount] = useState(0); const [name, setName] = useState('');
One state to track if a menu is open, another to hold a list of items.
React
const [isOpen, setIsOpen] = useState(false); const [items, setItems] = useState([]);
Sample Program
This component uses two separate state variables: one for a number counter and one for a text input. They update independently when you click the button or type in the input.
React
import React, { useState } from 'react'; export default function MultipleStates() { const [count, setCount] = useState(0); const [name, setName] = useState(''); return ( <main> <section> <h2>Counter</h2> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)} aria-label="Increase count">Increase</button> </section> <section> <h2>Name Input</h2> <input type="text" value={name} onChange={e => setName(e.target.value)} aria-label="Name input" placeholder="Enter your name" /> <p>Your name is: {name}</p> </section> </main> ); }
OutputSuccess
Important Notes
Updating one state variable does not affect the others.
Keep state variables focused on one piece of data each for clarity.
Summary
Multiple state variables help manage different data separately.
Each state has its own setter function to update it.
This approach keeps your component organized and easier to understand.