React Native
Object state
Learn object state management.
Object as state
Holding state as an object makes it easier to manage related values together. For a form you might write const [form, setForm] = useState({'{ name: '', email: '' }'}).
Be careful when updating object state: setForm({ name: 'Alex' }) drops email. The setter does not merge your object with the old one; it replaces it entirely.
To fix this, use the spread operator: setForm({'{ ...form, name: 'Alex' }'}). The three dots copy the old fields, then only name is changed. This is called a merge.
Care with object state
The most common mistake with object state is updating a field without spread. Writing setForm({ name: 'Alex' }) destroys email; the email disappears from the screen.
The correct pattern is always setForm({'{ ...form, name: 'Alex' }'}). This creates a new object; it copies the old fields and only changes the named one. React sees the new reference and re-renders.
The same rule applies to array state: setItems({'{...items, newItem}'}). Without a reference change, React does not notice the update.
Exercise A form with object state
Write an App component. Define form with useState({'{ name: '', city: '' }'}). An updateName function should call setForm({'{ ...form, name: text }'}). Show name and city with two <Text>. Export the App function.
Show example solution
function App() {
const [form, setForm] = useState({ name: 'Alex', city: 'London' });
const updateName = (text) => {
setForm({ ...form, name: text });
};
return (
<>
<Text>{form.name}</Text>
<Text>{form.city}</Text>
</>
);
}
export default App;
Test yourself
-
Update with spread
import { useState } from 'react';
function App() {
const [form, setForm] = useState({ name: '', email: '' });
const updateName = (text) => {
setForm({ ____, name: text });
};
}
Show answer
import { useState } from 'react';
function App() {
const [form, setForm] = useState({ name: '', email: '' });
const updateName = (text) => {
setForm({ ...form, name: text });
};
}
-
Object state steps
- useState({...})
- Initial object
- ...form
- Copies old fields
- name: text
- New field value
- new reference
- Triggers render
-
What mistake is common with object state?
- Not calling useState
- Updating a field without spread
- Not naming the setter
- Holding a number in state
Show answer
Updating a field without spread — updating without spread destroys the other fields.
Next lesson: Summary - State