useState
- React Native course
- Beginner
- Lesson 20/116
- 6 min
Learn counter state with useState.
What is useState?
useState is a React hook. It lets a component hold state. When state changes, the component re-renders and the screen updates.
Usage: const [count, setCount] = useState(0);. Here count is the current value and setCount is the function that changes it. 0 is the initial value.
You must import useState from the react package: import { useState } from 'react';.
Counter with useState
We will hold the counter with useState instead of a constant 0. This way the screen updates automatically as the value changes.
We will make two changes: first add the line import { useState } from 'react';; second place const [count, setCount] = useState(0); inside the App component.
Finally we will replace the 0 in <Text>Counter: 0</Text> with {count}.
Practice Add useState
Add useState to the existing skeleton. Import useState from react. Inside the App component declare const [count, setCount] = useState(0);. Show Counter: {count} inside <Text>.
Starter code
import { View, Text } from 'react-native';
export default function App() {
return (
<View>
<Text>Counter: 0</Text>
</View>
);
}Sample solution
import { View, Text } from 'react-native';
import { useState } from 'react';
export default function App() {
const [count, setCount] = useState(0);
return (
<View>
<Text>Counter: {count}</Text>
</View>
);
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 useState call
const [count, setCount] = ____(0);
const [count, setCount] = useState(0);
Explanation: useState(0) creates state with initial value 0.
2 How do you use useState?
- const count = useState(0);
- const [count] = useState;
- const [count, setCount] = useState(0); Correct answer
- const setCount = useState(0);
Explanation: useState returns a value and a setter.
3 Match the useState parts
| Term | Meaning |
|---|---|
useState |
Hook |
count |
Value |
setCount |
Setter |
0 |
Initial value |