Component Pattern

Controlled / Uncontrolled Component

Controlled Component

  • Controlled components are form elements (like input, textarea, or select) that are managed by React state.

import React, { useState } from 'react';

function ControlledComponent() {
  const [value, setValue] = useState('');

  const handleChange = (event) => {
    setValue(event.target.value);
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    alert('A name was submitted: ' + value);
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name:
        <input type="text" value={value} onChange={handleChange} />
      </label>
      <button type="submit">Submit</button>
    </form>
  );
}

export default ControlledComponent;

Uncontrolled Component

  • Uncontrolled components in React manage their own state internally rather than relying on React state.

  • Using the ref attribute to create a reference (this.inputRef) to the DOM node of the input field to access the internal state

Pro & Con

Controlled Component

  • Using controlled components ensures that the form data is always in sync with the React state. This predictability comes from having a single source of truth for the data and easier to debug

  • Easier to integrate with form library, e.g: React Hook Form

Uncontrolled Component

  • Applicable for the form that is straightforward with minimal input fields and does not require complex validation or dynamic updates based on other form inputs.

  • Validation logic often involves accessing and checking each input's value directly through refs (ref.current.value). This approach can lead to more manual and error-prone validation code, especially in forms with complex validation requirements.

Composable Component

  • Easy to implement container & presentation pattern, state management & logic is on parent component (container layer) and pass the prop into child-component (presentation layer) through implementing context provider

  • Easier to understand the relationship between components and clear structure

  • Suitable to implement it with Form , Table

References

Last updated

Was this helpful?