← Back to Chapters

useState Hook

⚛️ useState Hook

? Quick Overview

The useState hook is used to manage state in functional components in React Native. It allows components to store, update, and react to changing data such as counters, form inputs, toggles, and UI state.

? Key Concepts

  • State represents dynamic data in a component
  • useState returns a state value and a setter function
  • Updating state triggers re-render
  • State is preserved between renders

? Syntax / Theory

The useState hook is imported from React and called inside a functional component.

? View Code Example
// Basic syntax of useState hook
const [state, setState] = useState(initialValue);

? Code Example

? View Code Example
// Counter & Toggle example using useState in React Native
import React, { useState } from "react";
import { View, Text, Button } from "react-native";

export default function App() {
  // 1. Number State
  const [count, setCount] = useState(0);
  
  // 2. Boolean State
  const [isActive, setIsActive] = useState(false);

  return (
    <View>
      {/* Counter Logic */}
      <Text>Count: {count}</Text>
      <Button title="Increase" onPress={() => setCount(count + 1)} />

      {/* Toggle Logic */}
      <Text>Status: {isActive ? "Active" : "Inactive"}</Text>
      <Button 
        title="Toggle" 
        onPress={() => setIsActive(!isActive)} 
      />
    </View>
  );
}

? Interactive Simulator

Test the logic below. This simulates two independent state variables: a number (Count) and a boolean (Status).

 
Count: 0
 
Status: Inactive

States are independent. Updating one does not reset the other.

? Live Output / Explanation

What Happens?

  • Count State: Starts at 0. Clicking "Increase" calls setCount(prev + 1).
  • Status State: Starts at false. Clicking "Toggle" calls setIsActive(!isActive).
  • React Native re-renders the UI whenever either state changes.

? Interactive Explanation

Each button press calls its specific setter function. Notice how the "Count" and the "Status" do not interfere with each other. This is because you can have multiple useState hooks in a single component.

? Use Cases

  • Counters and score tracking
  • Form input handling
  • Theme toggles (Light/Dark mode)
  • Show / hide UI elements (Modals)

✅ Tips & Best Practices

  • Always use setter function to update state
  • Never modify state variables directly
  • Use multiple states instead of complex objects when possible
  • Keep state minimal and focused

? Try It Yourself

  1. Create a toggle button using useState
  2. Build a simple like counter
  3. Change text color based on state