Loading...

What are controlled and uncontrolled components in React?

What are controlled and uncontrolled components in React?

Data flow and user experience are crucial aspects of any React application. To ensure that these elements run smoothly and efficiently, understanding the difference between controlled and uncontrolled components is paramount. Grasping this concept will aid developers in ensuring that data flows seamlessly and that the user experience is optimized.

Understanding Controlled Components

Controlled components in React are a powerful tool, acting as components where React is responsible for managing and controlling the data (or state). This approach guarantees that there’s a single source of truth for the data, ensuring uniformity across the application.

What is a Controlled Component?

In essence, a controlled component is one where the data, typically input form data, is handled by the React state mechanism. Rather than allowing the DOM to manage this data, React takes charge, ensuring that data handling and changes are consistent with the React paradigm.

How Controlled Components Work

The underlying principles of controlled components are simple yet powerful:

  • Using state to store form values: Every time a user interacts with a form element, like typing into an input field, the value is stored in the component’s local state.
  • Using setState or the useState hook: To update the stored values in the state, one would traditionally use the setState method in class components. With the introduction of React hooks, the useState hook provides a more concise way to manage state in functional components.
  • Passing state as props to child components: This allows child components to receive and display the data, ensuring a single source of truth and a consistent data flow.

Examples of Controlled Components

Let’s delve into a few examples:

  • Controlled input text field:
    function TextInput() {
    const [text, setText] = useState('');

    return (
    <input type="text" value={text} onChange={e => setText(e.target.value)} />
    );
    }

  • Controlled checkbox:
    function CheckBox() {
    const [checked, setChecked] = useState(false);

    return (
    <input type="checkbox" checked={checked} onChange={() => setChecked(!checked)} />
    );
    }

  • Controlled select dropdown:
    function SelectBox() {
    const [selectedOption, setSelectedOption] = useState('');

    return (
    <select value={selectedOption} onChange={e => setSelectedOption(e.target.value)}>
    <option value="option1">Option 1</option>
    <option value="option2">Option 2</option>
    </select>
    );
    }

Benefits of Controlled Components

Adopting controlled components in your React projects brings with it a plethora of advantages:

Predictable Data Flow

With controlled components, data flow is consistent and reliable. Since React maintains control over form values and their updates, there’s minimal chance for unexpected behaviors or discrepancies in data representation.

Integration with State Management Libraries

Controlled components play nicely with popular state management libraries, such as Redux. This seamless integration ensures that application-wide state management is more intuitive and effective, allowing developers to handle complex data manipulations efficiently.

Enhanced Data Manipulation

Before updating the state, developers have the luxury to intercept and manipulate the data. This means validation, formatting, or any other data transformation can be done to ensure the integrity and correctness of the data being stored.

User Feedback

Controlled components, especially in forms, can offer immediate feedback to users. Whether it’s showing an error when a user types in an invalid email or displaying a character count for a text area, controlled components allow for dynamic and interactive user experiences that enhance overall usability.

Understanding Uncontrolled Components

Diving into components that maintain their own internal state without external control.

What is an Uncontrolled Component?

An uncontrolled component in React is one that stores its own state internally and does not control its value through the React state mechanism. Instead of being managed by React’s state system, it relies directly on the DOM to provide its current value.

How Uncontrolled Components Work

Uncontrolled components have a few defining characteristics:

  • Using ref to get values directly from the DOM: Instead of using an event handler to read the input’s value, you can obtain the value directly through ref.
  • Reduced reliance on React’s state: Since these components don’t synchronize their state with React’s state mechanism, they might feel more familiar to developers who’ve worked with vanilla JavaScript.

Examples of Uncontrolled Components

  1. Uncontrolled input text field using ref:
1class MyComponent extends React.Component {
2 constructor(props) {
3 super(props);
4 this.inputRef = React.createRef();
5 }
6
7 handleSubmit = () => {
8 alert('A name was submitted: ' + this.inputRef.current.value);
9 }
10
11 render() {
12 return (
13 <form onSubmit={this.handleSubmit}>
14 <input type="text" ref={this.inputRef} />
15 <button type="submit">Submit</button>
16 </form>
17 );
18 }
19}
  1. Uncontrolled checkbox:
1class CheckboxComponent extends React.Component {
2 checkboxRef = React.createRef();
3
4 handleCheck = () => {
5 alert('Checkbox is ' + (this.checkboxRef.current.checked ? 'checked' : 'unchecked'));
6 }
7
8 render() {
9 return (
10 <div>
11 <input type="checkbox" ref={this.checkboxRef} onChange={this.handleCheck} />
12 <label>Click me</label>
13 </div>
14 );
15 }
16}
  1. Default values in uncontrolled components:
    By using the defaultValue property for inputs, you can set an initial value without controlling it through React’s state.
<input type="text" defaultValue="Default text" ref={this.inputRef} />

Benefits of Uncontrolled Components

Simplicity and Quick Prototyping

For smaller projects or forms where state management might be overkill, uncontrolled components can be faster to implement. You can avoid setting up state and event handlers for every input, streamlining the development process.

Reduced React Re-renders

Each time a controlled component’s value changes, it triggers a re-render in React. While this is often optimized and isn’t a concern, in some high-frequency update scenarios, uncontrolled components can offer performance advantages since they don’t tie into React’s re-render mechanism for every value change.

Traditional HTML Form Behavior

For developers transitioning from vanilla JavaScript, uncontrolled components might feel more intuitive. They behave more like traditional HTML form elements.

When to use Controlled vs. Uncontrolled Components

Project Size and Complexity

For smaller projects with a few inputs, uncontrolled components can be more straightforward. But as projects grow and require more interactivity and data sharing among components, controlled components become more beneficial.

Data Validation Requirements

Controlled components can offer more fine-grained control over input validation. If real-time validation or feedback is a requirement, controlled components are typically more suited.

State Management Preferences

If you’re comfortable with React’s state and prefer a single source of truth for form values, controlled components are the way to go. But if you want a more direct approach that’s closer to traditional HTML, uncontrolled components have their merits.

Performance Considerations

While uncontrolled components might lead to fewer re-renders in specific scenarios, controlled components, when used correctly, are optimized and shouldn’t pose performance issues for most use cases.

Common Misconceptions

  • “Uncontrolled components are bad practice”: This isn’t true. Both controlled and uncontrolled components have their use cases in React.
  • “Uncontrolled components can’t be validated”: They can still be validated, but the process might be more manual compared to controlled components.

Best Practices

  • Use Controlled Components when: You need tight control over form values and interactions, require real-time validation, or have complex forms.
  • Use Uncontrolled Components when: Rapid prototyping, when building simpler forms, or when you want to minimize React’s involvement.

Conclusion

Choosing between controlled and uncontrolled components isn’t about one being superior to the other. It’s about evaluating the needs of your specific project and making an informed decision. Both approaches have their strengths and use cases.

Further Reading and Resources

  • React’s official documentation on Forms offers a deep dive into both controlled and uncontrolled components.
  • Libraries like Formik and react-hook-form can aid in managing form state and validation.
  • For those on codedamn looking to dive deeper, there are plenty of courses and tutorials that cover React forms in depth.

Sharing is caring

Did you like what Mayank Sharma wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far

Curious about this topic? Continue your journey with these coding courses: