JavaScript and React course ยท Module 2: Components and Props

Controlled vs uncontrolled components

5 min read ยท
In this lesson5

On a space station, every system operates in one of two modes: either the command center has full control over the parameters (manual mode), or the system operates autonomously and the center only reads data when needed (automatic mode). In React, forms and input fields work analogously - they can be controlled by component state or uncontrolled, where the browser manages their value.

Controlled Component

A controlled component is one where React is the "single source of truth" for the form field value. Every value change goes through the component state:

import React, { useState } from 'react';

function PilotLogin() {
  const [pilotName, setPilotName] = useState('');
  const [accessCode, setAccessCode] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log(`Pilot login: ${pilotName}, code: ${accessCode}`);
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Pilot name:
        <input
          type="text"
          value={pilotName}
          onChange={(e) => setPilotName(e.target.value)}
        />
      </label>
      <label>
        Access code:
        <input
          type="password"
          value={accessCode}
          onChange={(e) => setAccessCode(e.target.value)}
        />
      </label>
      <button type="submit">Log in</button>
    </form>
  );
}

Key elements of a controlled component:

  1. value={stateVariable} - field value is bound to state
  2. onChange - every change updates state via setState
  3. React state is the single source of truth - the browser displays what React tells it to

Data flow in a controlled component

When a user types a character in a text field:

  1. The browser detects the change and fires onChange
  2. The handler updates state via setState
  3. React re-renders the component with the new value
  4. The field displays the new value from state

This is a closed loop - React controls every character typed into the form.

Uncontrolled Component

In an uncontrolled component, the browser (DOM) manages the field value. React doesn't track every change - instead, it reads the value only when it needs it (e.g., when submitting a form). To read values from the DOM, we use ref (references):

import React, { useRef } from 'react';

function QuickSearch() {
  const searchInputRef = useRef(null);

  const handleSearch = (e) => {
    e.preventDefault();
    // We read the value directly from the DOM
    const query = searchInputRef.current.value;
    console.log(`Searching: ${query}`);
  };

  return (
    <form onSubmit={handleSearch}>
      <input
        type="text"
        ref={searchInputRef}
        defaultValue=""
        placeholder="Search the station database..."
      />
      <button type="submit">Search</button>
    </form>
  );
}

Key elements of an uncontrolled component:

  1. ref={reference} - handle to the DOM element
  2. defaultValue instead of value - sets the initial value but doesn't control further changes
  3. ref.current.value - reading value from the DOM when needed

useRef - accessing DOM elements

The useRef hook creates an object with a current property that points to the DOM element after the component mounts:

import React, { useRef } from 'react';

function FocusInput() {
  const inputRef = useRef(null);

  const handleClick = () => {
    // Direct access to DOM element
    inputRef.current.focus();
    inputRef.current.style.borderColor = '#4caf50';
  };

  return (
    <div>
      <input ref={inputRef} type="text" placeholder="Click the button..." />
      <button onClick={handleClick}>Set focus</button>
    </div>
  );
}

useRef has an important characteristic: changing ref.current does not cause a re-render of the component. This makes it ideal for storing references to DOM elements without impacting performance.

When to use controlled vs uncontrolled?

ScenarioControlledUncontrolled
Real-time validation (every character)yes-
Formatting data on the fly (e.g., card number)yes-
Conditionally disabling the submit buttonyes-
Dynamic fields dependent on each otheryes-
Simple "submit and forget" form-yes
Integration with external code (non-React)-yes
Maximum performance (no re-renders per keystroke)-yes

General rule: use controlled components by default. Use uncontrolled ones only when you have a specific reason (performance, integration with an external library, file upload). An <input type="file"> field is always uncontrolled.

Form validation with a controlled component

A great advantage of controlled components is the ability to validate data in real time:

function CrewRegistration() {
  const [name, setName] = useState('');
  const [age, setAge] = useState('');

  const validate = () => {
    const newErrors = {};
    if (name.length < 2) newErrors.name = 'Name must be at least 2 characters';
    if (!age || age < 18 || age > 65) newErrors.age = 'Age: 18-65 years';
    return newErrors;
  };
  // Errors are computed on every render - live, keystroke by keystroke
  const errors = validate();
  const isValid = Object.keys(errors).length === 0;

  const handleSubmit = (e) => {
    e.preventDefault();
    if (isValid) {
      console.log(`Registration: ${name}, age: ${age}`);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <input
          value={name}
          onChange={(e) => setName(e.target.value)}
          placeholder="Crew member name"
        />
        {name && errors.name && <span style={{color: 'red'}}>{errors.name}</span>}
      </div>
      <div>
        <input
          type="number"
          value={age}
          onChange={(e) => setAge(e.target.value)}
          placeholder="Age"
        />
        {age && errors.age && <span style={{color: 'red'}}>{errors.age}</span>}
      </div>
      <button type="submit" disabled={!isValid}>Register</button>
    </form>
  );
}

In a controlled component, we can continuously check data, display error messages, and conditionally enable the submit button - this is impossible in an uncontrolled component without additional code.

Summary

Controlled components give you full power over the form - React tracks every value change, enabling real-time validation, formatting, and dynamic behavior. Uncontrolled components are simpler - the browser manages the value, and React reads it through ref only when needed. In most cases, controlled components are the better choice, but uncontrolled ones have their place in simple forms and integrations.

Code for this lesson: App.jsx
import React, { useState, useRef } from 'react';

// =============================================
// CONTROLLED VS UNCONTROLLED COMPONENTS
// =============================================

// --- 1. Controlled component ---
function ControlledLogin() {
  const [pilotName, setPilotName] = useState('');
  const [accessCode, setAccessCode] = useState('');
  const [message, setMessage] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();
    if (pilotName.length < 2) {
      setMessage('Name must have at least 2 characters!');
      return;
    }
    if (accessCode.length < 4) {
      setMessage('Code must have at least 4 characters!');
      return;
    }
    setMessage(`Welcome aboard, ${pilotName}!`);
  };

  return (
    <div style={{
      backgroundColor: '#f5f5f5',
      padding: '20px',
      borderRadius: '12px',
      marginBottom: '20px'
    }}>
      <h3 style={{ color: '#2196f3', marginTop: 0 }}>
        Controlled login form
      </h3>
      <p style={{ fontSize: '13px', color: '#666' }}>
        React controls every character - value + onChange
      </p>
      <form onSubmit={handleSubmit}>
        <div style={{ marginBottom: '12px' }}>
          <label style={{ display: 'block', marginBottom: '4px', fontWeight: 'bold' }}>
            Pilot name:
          </label>
          <input
            type="text"
            value={pilotName}
            onChange={(e) => setPilotName(e.target.value)}
            placeholder="Enter name..."
            style={{
              padding: '8px 12px', width: '100%', boxSizing: 'border-box',
              borderRadius: '6px', border: '1px solid #ccc'
            }}
          />
          <small style={{ color: '#999' }}>
            Entered: {pilotName.length} characters
          </small>
        </div>
        <div style={{ marginBottom: '12px' }}>
          <label style={{ display: 'block', marginBottom: '4px', fontWeight: 'bold' }}>
            Access code:
          </label>
          <input
            type="password"
            value={accessCode}
            onChange={(e) => setAccessCode(e.target.value)}
            placeholder="Min. 4 characters..."
            style={{
              padding: '8px 12px', width: '100%', boxSizing: 'border-box',
              borderRadius: '6px', border: '1px solid #ccc'
            }}
          />
        </div>
        <button
          type="submit"
          disabled={pilotName.length < 2 || accessCode.length < 4}
          style={{
            padding: '10px 20px', backgroundColor: '#2196f3', color: 'white',
            border: 'none', borderRadius: '6px', cursor: 'pointer',
            opacity: (pilotName.length < 2 || accessCode.length < 4) ? 0.5 : 1
          }}
        >
          Log in
        </button>
      </form>
      {message && (
        <p style={{
          marginTop: '12px', padding: '8px 12px',
          backgroundColor: message.includes('Welcome') ? '#e8f5e9' : '#ffebee',
          borderRadius: '6px'
        }}>
          {message}
        </p>
      )}
    </div>
  );
}

// --- 2. Uncontrolled component with useRef ---
function UncontrolledSearch() {
  const searchRef = useRef(null);
  const [result, setResult] = useState('');

  const handleSearch = (e) => {
    e.preventDefault();
    const query = searchRef.current.value;
    setResult(query
      ? `Searching the station database: "${query}"`
      : 'Enter a search phrase!'
    );
  };

  const handleFocus = () => {
    searchRef.current.focus();
    searchRef.current.style.borderColor = '#4caf50';
  };

  return (
    <div style={{
      backgroundColor: '#f5f5f5',
      padding: '20px',
      borderRadius: '12px',
      marginBottom: '20px'
    }}>
      <h3 style={{ color: '#4caf50', marginTop: 0 }}>
        Uncontrolled search form
      </h3>
      <p style={{ fontSize: '13px', color: '#666' }}>
        The DOM manages the value - ref + defaultValue
      </p>
      <form onSubmit={handleSearch}>
        <div style={{ display: 'flex', gap: '8px', marginBottom: '12px' }}>
          <input
            type="text"
            ref={searchRef}
            defaultValue=""
            placeholder="Search the station database..."
            style={{
              padding: '8px 12px', flex: 1,
              borderRadius: '6px', border: '1px solid #ccc'
            }}
          />
          <button type="submit" style={{
            padding: '8px 16px', backgroundColor: '#4caf50', color: 'white',
            border: 'none', borderRadius: '6px', cursor: 'pointer'
          }}>
            Search
          </button>
        </div>
      </form>
      <button onClick={handleFocus} style={{
        padding: '6px 12px', backgroundColor: '#ff9800', color: 'white',
        border: 'none', borderRadius: '6px', cursor: 'pointer', fontSize: '12px'
      }}>
        Set focus on the field (ref.current.focus)
      </button>
      {result && (
        <p style={{
          marginTop: '12px', padding: '8px 12px',
          backgroundColor: '#e8f5e9', borderRadius: '6px'
        }}>
          {result}
        </p>
      )}
    </div>
  );
}

// --- MAIN APPLICATION ---
export default function App() {
  return (
    <div style={{
      fontFamily: 'Arial, sans-serif',
      maxWidth: '700px',
      margin: '0 auto',
      padding: '24px'
    }}>
      <header style={{
        background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
        padding: '20px',
        borderRadius: '12px',
        color: 'white',
        textAlign: 'center',
        marginBottom: '24px'
      }}>
        <h1 style={{ margin: 0 }}>Controlled vs Uncontrolled</h1>
        <p style={{ margin: '8px 0 0', opacity: 0.9 }}>
          Two approaches to forms in React
        </p>
      </header>

      <ControlledLogin />
      <UncontrolledSearch />

      <div style={{
        padding: '16px',
        backgroundColor: '#1a1a2e',
        borderRadius: '8px',
        color: '#ccc',
        fontSize: '14px'
      }}>
        <strong style={{ color: '#ffd700' }}>Summary:</strong>
        <ul style={{ margin: '8px 0 0', paddingLeft: '20px' }}>
          <li><span style={{ color: '#2196f3' }}>Controlled</span> - value + onChange, React tracks every character</li>
          <li><span style={{ color: '#4caf50' }}>Uncontrolled</span> - ref + defaultValue, the DOM manages the value</li>
          <li><span style={{ color: '#ff9800' }}>useRef</span> - access to a DOM element without re-renders</li>
          <li><span style={{ color: '#e91e63' }}>Validation</span> - easier in controlled (real-time)</li>
        </ul>
      </div>
    </div>
  );
}

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What characterizes a controlled form component in React?

  2. 2. When is an uncontrolled component a better choice than a controlled one?

  3. 3. What is useRef used for in the context of uncontrolled components?

  4. 4. What is the difference between the value and defaultValue attributes in React?

  5. 5. What is the main advantage of a controlled form component?

  6. 6. How do you read the value of an input field in an uncontrolled component?

  7. 7. Why should React components be named using PascalCase convention (e.g., UserProfile)?

  8. 8. Which of the following signals best indicates that a component should be split into smaller ones?

  9. 9. What does the Single Responsibility Principle mean in the context of React components?

  10. 10. What is the recommended practice for organizing components in files?

  11. 11. What is the difference between unit tests and integration tests for React components?

Hands-on tasks in the game

  • Click in order

    Arrange the controlled input in JSX (value first, then onChange):

  • Vertical ordering

    Arrange the data flow stages in a controlled form component:

  • Vertical ordering

    Arrange the elements from controlled to uncontrolled approach:

  • Code editor

    In the App component (or a component that App renders), create a controlled form with the fields name (text input), rank (a select with a few ranks) and experience (input type='number'). Each field has value and onChange. The button must be disabled when name is empty.

  • Code editor

    In the App component (or a component that App renders), create an uncontrolled search form: an input without value, with a ref from useRef (and optionally defaultValue). On submit, read the value via ref.current.value (e.g. print it with console.log). Add a separate button that focuses the field via ref.current.focus().

  • Code editor

    Create a withSecurityProtocol(WrappedComponent, requiredLevel) HOC that returns a new component. The new component checks the clearanceLevel prop: when it is lower than requiredLevel, it displays an โ€œAccess deniedโ€ message; otherwise it renders WrappedComponent with all the props it received plus isSecured={true}.

  • Click in order

    Click elements in the order they should appear in a React component file:

  • Code editor

    The SpaceStation component in the editor does too much at once. Extract three components from it: StationHeader({ name, status }) with the station name and status, CrewList({ members }) with the crew list, and SystemPanel({ systems }) with the list of systems. Use props destructuring and default values (e.g. members = []), and let SpaceStation only compose these three components.

  • Vertical ordering

    Arrange the steps of refactoring a large component into smaller ones:

  1. QuestionControlled Component
  2. Click in orderControlled input syntax
  3. Put in orderData flow in a controlled component
  4. Put in orderControlled vs uncontrolled component elements
  5. QuestionChoosing Between Controlled and Uncontrolled
  6. QuestionuseRef Hook
  7. Coding taskPractice: Controlled Form
  8. Questionvalue vs defaultValue Attribute
  9. QuestionControlled Component Advantage
  10. QuestionReading the value via ref
  11. Coding taskPractice: Uncontrolled Form with useRef
  12. Coding taskPractice: withSecurityProtocol HOC
  13. QuestionComponent Naming Convention
  14. Click in orderComponent file structure
  15. QuestionWhen to Split a Component
  16. Coding taskPractice: Component Refactoring
  17. Put in orderComponent refactoring steps
  18. QuestionSingle Responsibility Principle
  19. QuestionComponent File Organization
  20. QuestionComponent Testing Strategy

Useful articles