🚀 React Controlled vs. Uncontrolled Components 🚀

Zeeshan SafdarZeeshan Safdar
1 min read

As a React developer, mastering form management is essential, and understanding the difference between controlled and uncontrolled components is a key part of that journey! 🛠️

🔍 Uncontrolled Components

By default, form elements like <input>, <textarea>, or <select> maintain their own internal state within the DOM. This means React doesn’t have direct control over their values. You can still get the values using refs, but it becomes tricky to keep everything synchronized, especially in large applications.

Example:

<input type="text" ref={inputRef} />

Here, React doesn’t control the state, and retrieving the value requires extra effort (like using refs).


⚙️ Controlled Components

In contrast, controlled components allow React to take full ownership of the form’s state. The state of the form elements is stored and managed in the React component using useState or another state management technique. This gives more control, easier validation, and seamless synchronization.

Example:

const [inputValue, setInputValue] = useState("");

<input type="text" value={inputValue} onChange={(e) => setInputValue(e.target.value)} />

Here, React manages the value through state and updates the DOM when the state changes, keeping everything in sync! 🎯


🎯 Key Difference

  • Uncontrolled: State is handled by the DOM itself.

  • Controlled: State is handled by React, offering more control, reactivity, and consistency.

0
Subscribe to my newsletter

Read articles from Zeeshan Safdar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Zeeshan Safdar
Zeeshan Safdar

An accomplished front-end developer with a strong background in creating visually stunning and user-friendly websites and web applications. My deep understanding of web development principles and user-centered design allows me to deliver projects that exceed client expectations. I have a proven track record of success in delivering projects on time and to the highest standards, and I am able to work well in a team environment and am always looking for new challenges to take on.