Câu hỏi phỏng vấn Reactjs
Câu hỏi

What's the difference between a Controlled component and an Uncontrolled one in React?

Câu trả lời

In React, the distinction between controlled and uncontrolled components primarily revolves around how form data is managed and updated.

Controlled Components

Controlled components are those where the React component controls the state and updates of the form data. Here are the key characteristics and benefits of controlled components:

  1. State Management: The state of the form input is maintained in the component's state object. Every state update is handled through React's state management, ensuring the component re-renders whenever the state changes.

  2. Data Handling: In controlled components, the input value is set by the state, and any change to the input updates the state. This is typically done using event handlers like onChange that capture input changes and update the component's state accordingly[1][2][3][4].

  3. Predictability and Validation: Since all data passes through the component's state, it's easier to add validation, manipulate values, and implement conditional logic based on other state variables. This makes controlled components highly predictable and manageable[1][2][3][4].

  4. Example:

    class ControlledComponent extends React.Component {
        constructor(props) {
            super(props);
            this.state = { value: '' };
            this.handleChange = this.handleChange.bind(this);
        }
    
        handleChange(event) {
            this.setState({ value: event.target.value });
        }
    
        render() {
            return <input type="text" value={this.state.value} onChange={this.handleChange} />;
        }
    }

Uncontrolled Components

Uncontrolled components, on the other hand, delegate the management of the form data to the DOM itself rather than the React component.

  1. DOM Management: In uncontrolled components, form data is handled by the DOM. React components interact with the form data only when necessary, typically using a ref to access the form values when needed, such as during form submission[1][2][3][4].

  2. **Simplicity and Di...

junior

junior

Gợi ý câu hỏi phỏng vấn

senior

When to use useCallback , useMemo and useEffect ?

junior

What are Higher-Order Components (HOC) in React?

senior

What's a Pure Functional Component in React?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào