React Native
State update
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.
Exercise 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.
Show example solution
function App() {
const [count, setCount] = useState(0);
return (
<TouchableOpacity onPress={() => setCount(count + 1)}>
<Text>{count}</Text>
</TouchableOpacity>
);
}
export default App;
Test yourself
-
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>
);
}
Show answer
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>
);
}
-
count right after the setter?
- Still the old value
- The new value immediately
- Becomes undefined
- Throws an error
Show answer
Becomes undefined — React schedules the update, it does not change synchronously.
-
Match the update parts
- setCount
- Setter function
- count + 1
- New value computation
- onPress
- Event handler
- re-render
- Resulting screen update
Next lesson: Previous state