React Native theorytheory 0/50 · 0%
Hooks · easy

5. useState

Local component state.

`useState` gives a component a piece of state and a setter. Calling the setter schedules a re-render with the new value; it never mutates the old value directly.

import { useState } from "react";
import { Pressable, Text } from "react-native";

function Counter() {
  const [count, setCount] = useState(0);
  return (
    <Pressable onPress={() => setCount((c) => c + 1)}>
      <Text>{count}</Text>
    </Pressable>
  );
}

Prefer the updater-function form `setCount((c) => c + 1)` when the new value depends on the previous one — it avoids stale closures when several updates happen in quick succession.

Check your understanding

  1. 1. What does calling a useState setter do?

  2. 2. When should you use the updater-function form?

  3. 3. What does useState return?