React Native
useState
Learn state management with useState.
The useState hook
useState holds data that can change inside a component. This is called state. When state changes, the component re-renders and the screen updates.
You saw useState in the Counter project. Now we look at it more deeply. The call is const [count, setCount] = useState(0). Here count is the current value, setCount the function that updates it, and 0 the initial value.
It returns two values as an array, so we use destructuring. The first is for reading, the second for writing. Writing count = 5 directly does not update state; always use the setter.
Re-render on state change
When you call the setter, React takes the new value, runs the component again and updates the screen. This is called a re-render. The old value is gone.
Example: in setCount(count + 1), if count is 3, the new value becomes 4 and the component re-renders. The screen now shows 4.
State is always updated through the setter. Never assign directly; if you do, React misses the change and the screen stays the same. This is the most common beginner mistake.
Exercise Toggle text state
Write an App component. Define an on state with useState(true). Show a <Text> with {`{on ? 'On' : 'Off'}`}. Export the App function.
Show example solution
function App() {
const [on, setOn] = useState(true);
return <Text>{on ? 'On' : 'Off'}</Text>;
}
export default App;
Test yourself
-
What does useState return?
- Only a number
- An array: [value, setter]
- Only a function
- An object
Show answer
An array: [value, setter] — the first item is the value, the second the setter.
-
Complete the useState call
import { useState } from 'react';
import { Text } from 'react-native';
function App() {
const [count, setCount] = ____;
return <Text>{count}</Text>;
}
Show answer
import { useState } from 'react';
import { Text } from 'react-native';
function App() {
const [count, setCount] = useState(0);
return <Text>{count}</Text>;
}
-
Match the useState parts
- count
- Current value
- setCount
- Setter function
- 0
- Initial value
- re-render
- Happens on state change
Next lesson: State update