State update
- React Native course
- Beginner
- Lesson 72/116
- 5 min
Learn to update state with setState.
Updating with setState
The only way to update state is the setter function. From the counter: setCount(count + 1). Here the new value is a computation on the current value.
State does not change immediately after the setter call. React schedules the update; the new value appears on the next render. That is why reading count right after the setter returns the old value.
Calling the setter inside an event handler is the most common pattern. For example onPress={'{() => setCount(count + 1)}'}. Each press increments the counter and the screen updates.
The setter is async
When the setter is called, state does not change synchronously. React queues the update. So setCount(count + 1); setCount(count + 1); does not increment twice; the count in the second line is still the old value.
To fix this, use a functional update: setCount(prev => prev + 1). Here prev always holds the latest value. We will detail this in the next lesson.
This behavior is known as batch update. React merges multiple setState calls into a single render; it is good for performance but you must be careful with sequential calls.
Practice Write a counter button
Write an App component. Define a count state with useState(0). Show <Text>{`{count}`}</Text> inside a <TouchableOpacity>. Call setCount(count + 1) on onPress. Export the App function.
Starter code
import { useState } from 'react';
import { Text, TouchableOpacity } from 'react-native';
// write the counter button hereSample solution
function App() {
const [count, setCount] = useState(0);
return (
<TouchableOpacity onPress={() => setCount(count + 1)}>
<Text>{count}</Text>
</TouchableOpacity>
);
}
export default App;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Increment call
import { useState } from 'react';
import { Text, TouchableOpacity } from 'react-native';
function App() {
const [count, setCount] = useState(0);
return (
<TouchableOpacity onPress={() => ____(count + 1)}>
<Text>{count}</Text>
</TouchableOpacity>
);
}
import { useState } from 'react';
import { Text, TouchableOpacity } from 'react-native';
function App() {
const [count, setCount] = useState(0);
return (
<TouchableOpacity onPress={() => setCount(count + 1)}>
<Text>{count}</Text>
</TouchableOpacity>
);
}
Explanation: setCount takes the new value and updates state.
2 count right after the setter?
- Still the old value
- The new value immediately
- Becomes undefined Correct answer
- Throws an error
Explanation: React schedules the update, it does not change synchronously.
3 Match the update parts
| Term | Meaning |
|---|---|
setCount |
Setter function |
count + 1 |
New value computation |
onPress |
Event handler |
re-render |
Resulting screen update |