CodeBlanks Logo Icon CodeBlanks

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.

Practice 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.

Starter code

App.js
import { useState } from 'react';
import { Text } from 'react-native';

// write the object-state form here

Sample solution

App.js
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;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Update with spread

Question
import { useState } from 'react';

function App() {
  const [form, setForm] = useState({ name: '', email: '' });
  const updateName = (text) => {
    setForm({ ____, name: text });
  };
}
Answer
import { useState } from 'react';

function App() {
  const [form, setForm] = useState({ name: '', email: '' });
  const updateName = (text) => {
    setForm({ ...form, name: text });
  };
}

Explanation: ...form copies the old fields.

2 Object state steps

Term Meaning
useState({...}) Initial object
...form Copies old fields
name: text New field value
new reference Triggers render

3 What mistake is common with object state?

  • Not calling useState
  • Updating a field without spread Correct answer
  • Not naming the setter
  • Holding a number in state

Explanation: updating without spread destroys the other fields.

All lessons in Beginner