React Native

What is the difference between a controlled and uncontrolled component in React Native?

Medium
4
Added
A controlled component is one where the input value is controlled by React state, while an uncontrolled component maintains its own state and updates it through the DOM.

Solution Code

React Native
-- Example Code --
import React, { useState } from "react";
import { View, TextInput, Button, Text } from "react-native";

const ControlledComponent = () => {
  const [text, setText] = useState(" ");

  return (
    <View>
      <TextInput
        style={{ height: 40, borderColor: "gray", borderWidth: 1 }}
        onChangeText={text => setText(text)}
        value={text}
      />
      <Button title="Submit" onPress={() => alert(text)} />
    </View>
  );
};

const UncontrolledComponent = () => {
  return (
    <View>
      <TextInput
        style={{ height: 40, borderColor: "gray", borderWidth: 1 }}
        defaultValue="Hello"
      />
    </View>
  );
};

export default ControlledComponent;
Explanation
This code demonstrates the difference between controlled and uncontrolled components.

Guided Hints

{'hint': 'Controlled components use state to manage input values.'}
{'hint': 'Uncontrolled components manage state internally.'}