Controlled vs Uncontrolled Components

Controlled vs Uncontrolled Components

1. Controlled Components:

In a controlled component, the form element's value is controlled by React state. This means that the input's value is updated through the state, and any changes to the input are reflected via the onChangeText or similar event handlers.

Characteristics:

  • The input value is managed in the component's state.
  • You control the input programmatically.
  • React re-renders the component on input change to update the state.

Example of Controlled Component:

import React, { useState } from 'react';
import { TextInput, View, Text } from 'react-native';

const ControlledInput = () => {
  const [text, setText] = useState(''); // Controlled state

  return (
    <View>
      <TextInput
        value={text}  // Controlled by state
        onChangeText={newText => setText(newText)} // Updates state
        placeholder="Enter text"
        style={{ borderColor: 'gray', borderWidth: 1, padding: 16 }}
      />
      <Text>Entered Text: {text}</Text>
    </View>
  );
};

export default ControlledInput;
        

In this example, the TextInput's value is controlled by the text state, which is updated on every keystroke.


2. Uncontrolled Components:

In an uncontrolled component, the form element maintains its own internal state. You access the value via a reference (ref) when needed, rather than controlling the value via state.

Characteristics:

  • The input value is not tied to the component’s state.
  • You do not handle the input's state directly in the React component.
  • You access the value via a reference when required.

Example of Uncontrolled Component:

import React, { useRef } from 'react';
import { TextInput, View, Button } from 'react-native';

const UncontrolledInput = () => {
  const inputRef = useRef(null); // Ref for the input

  const handleSubmit = () => {
    const inputValue = inputRef.current.value; // Accessing value via ref
    console.log(inputValue);
  };

  return (
    <View>
      <TextInput
        ref={inputRef}  // Uncontrolled via ref
        placeholder="Enter text"
        style={{ borderColor: 'gray', borderWidth: 1, padding: 16 }}
      />
      <Button title="Submit" onPress={handleSubmit} />
    </View>
  );
};

export default UncontrolledInput;
        

In this example, the TextInput's value is not controlled by state but can be accessed using a ref when needed (e.g., when the submit button is pressed).

Key Differences:

  • Controlled Components: Value is tied to React state, making it easier to synchronize the input with other states or UI elements.
  • Uncontrolled Components: The component itself holds the value, and you access it through refs when necessary.


Choosing between controlled and uncontrolled components in React Native depends on your use case and how much control you need over the form elements. Here’s a guideline on when to use each:

1. Controlled Components:

When to Use:

  • Form validation: If you need to validate the form input in real-time (e.g., checking if the input is valid as the user types).
  • Dynamic behavior: When the form data influences other parts of the UI or application state (e.g., showing/hiding other form fields based on input).
  • Complex forms: If your form contains multiple dependent fields or logic (e.g., multi-step forms, conditional rendering).
  • Data sync: When the input needs to be in sync with the component's state, or shared across components, such as when you want to display the current input value elsewhere in the UI or send it to a backend.

Why Use Controlled Components:

  • Full control over the input’s state.
  • Allows for easy handling of input transformations (e.g., uppercase all letters, formatting numbers).
  • Makes it easy to integrate with form libraries (e.g., Formik) or handle submission logic cleanly.

Example Scenario:

If you have a form where the user’s input should be validated live (e.g., password strength checker or matching confirmation passwords), controlled components are ideal.

2. Uncontrolled Components:

When to Use:

  • Simple, isolated inputs: For simple forms where you don’t need to track the value of inputs in state until you submit the form or handle the input's value only when necessary (e.g., file inputs, a single field that you only read on submit).
  • Less frequent state updates: If you don’t need to update or re-render the component frequently as the user types. Uncontrolled components avoid unnecessary re-renders.
  • Performance considerations: For large forms where tracking every keystroke and updating state might cause performance issues, using uncontrolled components can reduce the overhead.

Why Use Uncontrolled Components:

  • Less boilerplate code, no need to write onChangeText or update state constantly.
  • Simpler for cases where you only care about the final value, such as form submission.

Example Scenario:

If you're building a basic contact form where you just need to capture the user's name, email, and message, and you only care about the data when the user submits the form, using uncontrolled components might make sense.

In general, controlled components are more flexible and powerful for complex use cases, while uncontrolled components are simpler for basic or isolated form fields.


In terms of performance optimisation, uncontrolled components are generally more optimised than controlled components, especially in larger forms or when dealing with complex UI re-renders. Here’s why:

1. Uncontrolled Components (More Optimised in Certain Cases):

  • Fewer Re-renders: Since uncontrolled components store their own state internally (in the DOM or Native UI layer), they don’t cause the React component to re-render on every keystroke. This means less CPU work when dealing with input-heavy forms where frequent changes are made.
  • Direct Access to the DOM/Native Element: Uncontrolled components rely on refs to interact with the input fields, which can be more efficient as the input value is only retrieved when necessary (e.g., on form submission) rather than tracked at every input change.
  • Lower Overhead: For simple forms where you don't need to synchronise the value with React state at every step, uncontrolled components avoid the overhead of managing state and calling setState or useState on every keystroke.

2. Controlled Components (Less Optimised, but Flexible):

  • More Re-renders: Controlled components are tied to the component’s state, meaning every change to the input value triggers a re-render of the component. This can become performance-intensive in forms with many fields or rapid input changes (e.g., when users are typing quickly).
  • More Flexible but Costly: While controlled components offer much more control and flexibility (such as real-time validation, dynamic field changes, etc.), managing state updates on every keystroke adds more overhead to the rendering cycle.

When Optimisation is Critical:

  • For Large Forms or High-Frequency Input: In scenarios with many form fields or where performance is crucial (e.g., an app with complex forms that get slow as the user types), uncontrolled components can offer better performance since they don’t cause continuous re-renders.
  • When Real-time Feedback is Needed: Even though controlled components tend to be slower, they are necessary when you need real-time feedback or when the input directly influences the state of other components. However, you can optimise the performance of controlled components by debouncing or throttling the state updates (e.g., delaying state updates until the user has stopped typing for a short period).

Optimisation Strategies:

  • Debouncing/Throttling Input Updates: If you're using controlled components but notice performance issues, you can debounce the updates so that the state only updates after the user has finished typing. This reduces the number of re-renders.
  • Selective Controlled/Uncontrolled Combination: In some forms, you might use a mix of controlled and uncontrolled components. For example, use controlled components only for fields where you need validation or real-time updates, while using uncontrolled components for simpler fields where state syncing isn't necessary.

Final Verdict:

  • Uncontrolled components are generally more optimised for performance due to fewer re-renders.
  • Controlled components offer more flexibility and are ideal for complex forms or real-time feedback, but can be less optimised unless careful optimisations (like debouncing) are applied.

In most cases, optimisation can be managed based on the specific needs of your app. For basic forms, uncontrolled components are often the better choice for performance; for dynamic or validated forms, controlled components give you the necessary flexibility despite the extra rendering overhead.

要查看或添加评论,请登录

Rakesh Kumar的更多文章

  • Javascript BrainStorming | Output Questions

    Javascript BrainStorming | Output Questions

    Here are the answers and explanations to the JavaScript questions: 1. Method vs.

  • Safe assignment operator

    Safe assignment operator

    The "safe assignment operator" in JavaScript refers to using logical operators to assign values in a safe way, ensuring…

    1 条评论

社区洞察

其他会员也浏览了