Summary - State
- React Native course
- Beginner
- Lesson 76/116
- 5 min
Combine useState, previous state and object state to write a form.
Summary - State
This group went deeper into state. useState returns a value and a setter; the setter triggers a re-render. Functional update keeps sequential changes safe.
Multiple state keeps independent values apart; object state manages related fields together and is safely updated with the spread operator. Now you will combine these in two mini tasks: first a counter with multiple state, then a form with object state.
Practice A counter with multiple state
Write an App component. Define two separate useState calls for count and step. Start step at 2 and count at 0. Call setCount(count + step) on a <TouchableOpacity> onPress. Show count with <Text>. Export the App function.
Starter code
import { useState } from 'react';
import { Text, TouchableOpacity } from 'react-native';
// write the counter with multiple state hereSample solution
function App() {
const [count, setCount] = useState(0);
const [step, setStep] = useState(2);
return (
<TouchableOpacity onPress={() => setCount(count + step)}>
<Text>{count}</Text>
</TouchableOpacity>
);
}
export default App;Practice A form with object state
Write an App component. Define form with useState({'{ name: '', city: '' }'}). An updateCity function should call setForm({'{ ...form, city: text }'}). Show name and city with two <Text>. Export the App function.
Starter code
import { useState } from 'react';
import { Text } from 'react-native';
// write the object-state form hereSample solution
function App() {
const [form, setForm] = useState({ name: 'Alex', city: 'London' });
const updateCity = (text) => {
setForm({ ...form, city: text });
};
return (
<>
<Text>{form.name}</Text>
<Text>{form.city}</Text>
</>
);
}
export default App;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match all the state concepts
| Term | Meaning |
|---|---|
useState |
Creates state |
setter |
Updates state |
prev => prev + 1 |
Functional update |
...form |
Spread in object state |
2 The safest path for object state?
- setForm({ ...form, name: text })
- setForm({ name: text })
- form.name = text Correct answer
- setForm()
Explanation: spread keeps the old fields and only changes one.