← Back to Chapters

Controlled Components in React Native

?️ Controlled Components in React Native

? Quick Overview

Controlled components are form elements whose values are fully managed by React state. In React Native, inputs like TextInput, Switch, and CheckBox become predictable when their value comes directly from state.

? Key Concepts

  • Component state is the single source of truth
  • User input updates state using handlers
  • UI always reflects the latest state value
  • Easier validation and debugging

? Syntax / Theory

A controlled component binds its value prop to state and updates that state on every change event. In React Native, this is commonly done using useState with onChangeText.

? Code Example(s)

? View Code Example
// Controlled TextInput example in React Native
import React, { useState } from "react";
import { View, Text, TextInput } from "react-native";

export default function App() {
  const [name, setName] = useState("");

  return (
    <View>
      <Text>Enter your name:</Text>
      <TextInput
        value={name}
        onChangeText={setName}
        placeholder="Type here"
      />
      <Text>You typed: {name}</Text>
    </View>
  );
}

? Live Output / Explanation

What happens?

As the user types into the input field, the state updates instantly. The displayed text below the input always matches the current state value.

? Interactive Example / Visual Flow

State flow in a controlled component:

  • User types text
  • onChangeText fires
  • State updates via setter
  • UI re-renders with new value

? React Native Simulator

Type in the phone screen to see how State drives the UI.

My App

Current Value:

?
Syncs
React State (Memory)
const [email, setEmail] = useState("");

// Current State Data:
{
  "email": ""
}

? Use Cases

  • Login and signup forms
  • Search inputs
  • Settings toggles
  • Real-time validation

✅ Tips & Best Practices

  • Always initialize state with a default value
  • Use controlled components for important user data
  • Keep form logic inside one component when possible

? Try It Yourself

  • Create a controlled password input
  • Add a character counter below TextInput
  • Disable submit button when input is empty