React Interview Questions

39 Questions
React.js

React.js

FrontendWeb Development

Question 17

What are controlled and uncontrolled components in React?

Answer:

In React, controlled and uncontrolled components are two different ways to manage form inputs and other DOM elements.

Controlled Components

A controlled component is a component that renders form elements whose values are controlled by the React state. In other words, the React state is the single source of truth for the form elements. Any changes to the form elements are handled through event handlers that update the state.

Characteristics:

  1. Single Source of Truth: The form input values are stored in the component's state.
  2. Explicit Handling: Changes to the input values are explicitly handled by event handlers.
  3. Predictable: Since the state drives the form inputs, it is easier to manage and debug.

Example:

import React, { useState } from 'react';

function ControlledForm() {
  const [name, setName] = useState('');

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

  const handleSubmit = (event) => {
    event.preventDefault();
    console.log('Submitted name:', name);
  };

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

export default ControlledForm;

Uncontrolled Components

An uncontrolled component is a component that manages form input values using the DOM itself. In this approach, you use refs to access the form values directly from the DOM instead of keeping them in the component's state.

Characteristics:

  1. DOM as Source of Truth: The form input values are stored in the DOM, not in the component's state.
  2. Implicit Handling: Changes to the input values are not explicitly handled by event handlers for updating the state.
  3. Simplicity: Easier to set up for simple forms where React state management might be overkill.

Example:

import React, { useRef } from 'react';

function UncontrolledForm() {
  const nameInputRef = useRef(null);

  const handleSubmit = (event) => {
    event.preventDefault();
    console.log('Submitted name:', nameInputRef.current.value);
  };

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

export default UncontrolledForm;

When to Use Controlled vs. Uncontrolled Components

Controlled Components:

  • Use when you need to validate or manipulate form input values before submitting.
  • Use when the form's state needs to be shared or manipulated by other parts of the application.
  • Use when you need to enforce input formats, such as currency or date formatting.

Uncontrolled Components:

  • Use when you need a simpler and quicker way to set up a form.
  • Use when you do not need to perform operations on the input values until form submission.
  • Use when you are integrating third-party libraries that manage form state outside of React.

Summary

Controlled and uncontrolled components provide two different approaches for handling form inputs in React. Controlled components use React state to manage input values, providing a single source of truth and more explicit control over form behavior. Uncontrolled components rely on the DOM to store input values, using refs to access them directly. The choice between the two depends on the complexity of the form and the specific requirements of the application.

Recent job openings