Forms in React

Expert-Level Explanation

Forms in React can be managed in two ways: using controlled or uncontrolled components. A controlled component has its form data controlled by React, while an uncontrolled component manages its own form data using the DOM. In controlled components, form data is handled by the state within the component. For uncontrolled components, refs are used to get form values from the DOM.

Creative Explanation

Controlled components are like having a remote-controlled toy car—you have full control over its movements through your remote (react state). Uncontrolled components are more like a free-rolling toy car—once you let it go, it moves on its own without your direct control, and you have to physically catch it to stop or change direction (using references).

Practical Explanation with Code

Controlled Component

import React, { useState } from 'react';

function MyForm() {
  const [inputValue, setInputValue] = useState('');

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

  return (
    <form>
      <input type="text" value={inputValue} onChange={handleChange} />
    </form>
  );
}

Uncontrolled Component

import React, { useRef } from 'react';

function MyForm() {
  const inputRef = useRef();

  const handleSubmit = (event) => {
    event.preventDefault();
    console.log('Input Value:', inputRef.current.value);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="text" ref={inputRef} />
      <button type="submit">Submit</button>
    </form>
  );
}

Real-World Example

In an e-commerce site, a controlled component would be useful for a live search bar where the search query is tied to the state, updating the search results as the user types. An uncontrolled component could be used for a simple newsletter signup form, where the form data (like email address) is retrieved from the DOM when the form is submitted.

Did you find this article valuable?

Support InterviewPro: Master Tech Fundamentals by becoming a sponsor. Any amount is appreciated!