CodeBlanks Logo Icon CodeBlanks

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.

Practice 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.

Starter code

App.js
import { useState } from 'react';
import { Text } from 'react-native';

// write the component here

Sample solution

App.js
function App() {
  const [on, setOn] = useState(true);
  return <Text>{on ? 'On' : 'Off'}</Text>;
}
export default App;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does useState return?

  • Only a number
  • An array: [value, setter] Correct answer
  • Only a function
  • An object

Explanation: the first item is the value, the second the setter.

2 Complete the useState call

Question
import { useState } from 'react';
import { Text } from 'react-native';

function App() {
  const [count, setCount] = ____;
  return <Text>{count}</Text>;
}
Answer
import { useState } from 'react';
import { Text } from 'react-native';

function App() {
  const [count, setCount] = useState(0);
  return <Text>{count}</Text>;
}

Explanation: useState(0) creates state with initial value 0.

3 Match the useState parts

Term Meaning
count Current value
setCount Setter function
0 Initial value
re-render Happens on state change

All lessons in Beginner