State with useState
useState works exactly like in web React — change state, and the screen redraws itself.
What you will learn
- Hold changing data with useState
- Update state on a tap
- See the screen re-render automatically
Same hook you already know
Good news: useState in React Native is the same hook from web React. You call it to keep a value that changes over time, and when you update that value the component re-renders so the screen stays in sync.
A tap counter
Here is the classic counter. Each tap adds one and the number on screen updates by itself:
import { useState } from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';
export default function App() {
const [count, setCount] = useState(0);
return (
<View style={styles.screen}>
<Text style={styles.big}>{count}</Text>
<Button title="Add one" onPress={() => setCount(count + 1)} />
</View>
);
}
const styles = StyleSheet.create({
screen: { flex: 1, justifyContent: 'center', alignItems: 'center' },
big: { fontSize: 48, marginBottom: 20 },
});Note: Output:
A big 0 in the middle with an "Add one" button.
Tap once -> 1, tap again -> 2, and so on.
You never tell the Text to change. Calling setCount re-renders the component, and the new count appears.
Watch out: Never change state directly. Writing count = count + 1 does nothing on screen. You must call the setter: setCount(count + 1). That is what triggers the re-render.
Tip: When the new value depends on the old one, use the function form to be safe: setCount(c => c + 1). It always uses the latest value, even if several updates happen quickly.
Q. Why does the number on screen update when you call setCount?
✍️ Practice
- Add a "Reset" button that sets the count back to 0.
- Add a "Subtract one" button next to "Add one".
🏠 Homework
- Build a simple step counter with +1, -1 and Reset buttons, showing the number large in the middle.