Multiple state
- React Native course
- Beginner
- Lesson 74/116
- 5 min
Learn multiple state variables.
Multiple state variables
A component can have several state variables. You call useState separately for each independent value. For example, in a form you might have one state for name and one for email.
Example: const [name, setName] = useState(''); and const [email, setEmail] = useState('');. Updating one does not affect the other; each triggers its own re-render.
Multiple state keeps things organized; grouping related values in an object is another option. You will see that in the Object state lesson. For now, we learn separate useState calls for independent values.
States are independent
Each of several states is independent. Updating one does not touch the others. For example setName('Alex') only changes name; email stays the same.
Both still live in the same component, so when one changes the component re-renders and both show their current values. This keeps the display in sync.
If two values always change together, grouping them in a single object may be cleaner. Otherwise, keeping them separate improves readability.
Practice A name and email form
Write an App component. Define two separate useState('') calls for name and email. Show the values with two <Text> tags. Export the App function.
Starter code
import { useState } from 'react';
import { Text } from 'react-native';
// write the form hereSample solution
function App() {
const [name, setName] = useState('Alex');
const [email, setEmail] = useState('alex@example.com');
return (
<>
<Text>{name}</Text>
<Text>{email}</Text>
</>
);
}
export default App;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How do you manage two states?
- State cannot be used Correct answer
- It cannot be done with one useState
- Only one state can be held
- With two separate useState calls
Explanation: each independent value gets its own useState call.
2 Add the second state
import { useState } from 'react';
function App() {
const [name, setName] = useState('');
const [____, setEmail] = useState('');
}
import { useState } from 'react';
function App() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
}
Explanation: email is the second state value.
3 Match multiple state concepts
| Term | Meaning |
|---|---|
name |
Name state |
setName |
Name setter |
email |
Email state |
setEmail |
Email setter |