DEV Community

Alexandra
Alexandra

Posted on

Navigating React's Controlled vs. Uncontrolled Components

Hello, hello 👋 If you're just starting your journey into React development, you might have encountered terms like "controlled components" and "uncontrolled components" and wondered what they mean and how they impact your code. Don't worry; you're not alone! In this beginner-friendly guide, we'll break down these concepts and help you understand when and how to use each approach effectively. 🐣

Controlled vs Uncontrolled inputs

Understanding Controlled Components 🎛️

Let's start with controlled components. In React, a controlled component is one where React controls the state of the component. This means that the component's state is managed by React itself, typically through props. When the state of a controlled component changes, React automatically updates the component to reflect those changes.

Imagine you have a form with an input field. For a controlled component input, you would define the input's value as a state variable and update it whenever the user types something new.



import React, { useState } from 'react';

export const ControlledEmailInput= () => {
  const [email, setEmail] = useState('');

  function handleEmailChange(event) {
    setEmail(event.target.value);
  }

  return (
    <input
      id="email"
      name="email"
      type="email"
      value={email}
      onChange={handleEmailChange}
    />
  );
}



Enter fullscreen mode Exit fullscreen mode

In the above example, the value of the email is controlled by React through the useState hook. When the email value is changed in the form by the user, the handleEmailChange event handle associated with the email input field will be triggered, causing the input to re-render with the new value.

Exploring Uncontrolled Components 🐟

Now, let's see the differences in uncontrolled components. Unlike controlled components, uncontrolled components manage their state internally. Instead of relying on React to manage state updates, uncontrolled components directly interact with the DOM to retrieve and update their state.




import React, { useRef } from 'react';

function UncontrolledEmailInput() {
  const inputRef = useRef(null);

  function handleEmailSubmit(event) {
    event.preventDefault();
    console.log('Email:', inputRef.current.value);
  }

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


Enter fullscreen mode Exit fullscreen mode

In this example, the input element maintains its own state via the DOM reference obtained through the useRef hook. When the form is submitted, the value of the input field is accessed directly from the DOM node using inputRef.current.value.

Key differences 🗝️

-- State Management:

In controlled components, React manages the component's state entirely. The component's state is stored in React's memory and updated through props.

In uncontrolled components, the component manages its state internally, directly interacting with the DOM. React does not control the component's state; instead, the component accesses and updates the DOM directly.

-- State sync:

Controlled components are tightly coupled with React's state management. Any changes to the component's state are reflected immediately in the component's UI.

Uncontrolled components maintain their state independently of React's state management. They do not rely on React to synchronize state changes with the UI.

-- Event Handlers for State Updates:

Controlled components rely on event handlers (e.g., onChange) to update the state. These event handlers modify the component's state, triggering re-renders as needed.

-- Predictable and Centralized State:

Controlled components offer predictability and centralization of state management. Developers have full control over the component's state and can easily manipulate it as needed.

-- Direct DOM Interaction:

Uncontrolled components interact directly with the DOM to access and update their state. This can lead to more efficient updates, especially for large or complex components.

Choosing the Right Approach 🤓

As a beginner, you might wonder which approach to use in your projects. The answer depends on your specific requirements and preferences. Controlled components offer a more predictable approach to state management, making them ideal for forms and components where the state needs to be synchronized with user input.

On the other hand, uncontrolled components can be simpler and more performant, especially for smaller components or when integrating with non-react code.

Conclusion

Controlled and uncontrolled components are essential concepts in React development. By understanding the differences between them and their respective use cases, you'll be better equipped to make informed decisions when building your React applications.

Remember, practice makes perfect! Experiment with both controlled and uncontrolled components in your projects to gain a deeper understanding of how they work and when to use them.

Happy coding! 🚀

Top comments (1)

Collapse
 
hjrobinson profile image
hjrobinson

Thanks for the article. I've been coding with React for a number of years but I never bothered to learn the difference. I haven't reviewed the official documentation for React but several years ago when I read it I couldn't figure things out (or maybe I was just lazy). But this made things easy to understand even for lazy people like me.