Understanding Controlled and Uncontrolled components in React (2023)

Lawrencefranklin

(Video) Controlled vs UnControlled Components In ReactJS | Interview Question

·

Follow

--

(Video) Controlled vs Uncontrolled Inputs - Reactjs - Absolute beginners
Understanding Controlled and Uncontrolled components in React (3)

One of the major concepts in React is the management of state and props, which are used to control the behavior and render the UI of a component. React provides both controlled and uncontrolled components, and this article will explore the differences between them and guide you about when to use each component type.

React provides several best practices and patterns that can be leveraged to improve the quality and maintainability of a React application. One such pattern is the controlled component and uncontrolled component pattern.

This article will explore the differences between controlled and uncontrolled components so you know when to apply each pattern.

In React, a controlled component is a component that has its state and behavior controlled by React. It takes its current value through props and changes its state through event handlers like onClick, onChange, etc.

An event handler responds to a specific event, such as a button click or a form submission. The event handler can update the state of the component, which will then trigger a re-render of the component. This means that the component will only change its behavior and render the UI based on the values of the props and state passed to it.

(Video) Controlled vs Uncontrolled Components | React Design Pattern -3

With controlled components, you can do instant fill validation. As the user is typing, you can quickly validate that the user is typing correctly. You can also do things like disable a button till all fields are validated. The controlled components pattern is the recommended way the React team advises you to handle inputs in React.

In contrast, an uncontrolled component is a component that has its state and behavior controlled by the DOM. You only get access to the component’s data when some event occurs. For example, when a user clicks the submit button on a form, we can only know what value the form’s input contains. This means that the component will change its behavior and render the UI based on the values of the DOM elements rather than the props and state passed to it.

One way to create an uncontrolled component is by using refs. A ref is a way to access the DOM element associated with a component, allowing you to manipulate it directly. This can be useful for cases where you don’t need to track the component’s state and need to access the value of an element.

In this article section, we will build a simple input field using React’s controlled component pattern and the uncontrolled component pattern. This will help you better understand how these two patterns compare. It is important to note that the controlled and uncontrolled component patterns do not affect the look of the input. These patterns only affect how the form data is managed and updated.

Here’s an example of a simple input field using the controlled component pattern in React:

import React, { useState } from "react";

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

const handleInputChange = (e) => {
setInputValue(e.target.value);
if (inputValue.includes("mad")) {
alert("No curse words please!");
}
};

const handleSubmit = () => {
alert(`The name of the blog is: ${inputValue}`);
};

return (
<div>
<form onSubmit={handleSubmit}>
<label>Blog Name: </label>
<input type="text" value={inputValue} onChange={handleInputChange} />
<button type="submit">Submit Form</button>
</form>
</div>
);
}

In this example, we use the hook to create a state variable called value and a function called setValue to update that state variable. We also defined a function called handleInputChange that will be called whenever the user types something into the input field.
The value prop on the input element is set to the inputValue state variable, which means that the input field will always display the current value of the state variable.
The onChange prop on the input element is set to the handleChange function, which means that whenever the user types something into the input field, the handleChange function will be triggered and update the inputValue state variable with the new value.

In the if statement, we verify whether the user has entered the offensive word "mad" and alert notification. This is possible even without the user submitting the form because every time the user modifies the input value, we keep track of that with the inputValue state.

When the user submits the form, the handleSubmit function gets triggered, and we're using the current value of inputValue (which we know is always in sync with the input field's value) to do something with that value (in this case, to alert the name of the blog).

Understanding Controlled and Uncontrolled components in React (4)

Here’s a screenshot for a clearer view.

Understanding Controlled and Uncontrolled components in React (5)

Here’s an example of the same input field using the uncontrolled component pattern in React:

import React, { useRef } from "react";

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

const handleSubmit = (event) => {
event.preventDefault();
alert("The name of the blog is: ", inputRef.current.value);
};

(Video) Full React Tutorial #27 - Controlled Inputs (forms)

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

In this example, we’re using the hook to create a reference to the input element. We're also defining a function called handleSubmit that will be called when the user submits the form.

The ref attribute on the input element is set to the inputRef reference, allowing us to access the input field's value later.
When the user submits the form, the handleSubmit function is called, which prevents the default form submission behavior (which would cause the page to refresh). Instead, we alert the value of the inputRef reference.

Using the uncontrolled pattern allows us to access the input field’s value without storing it in a state. This can be useful for simple forms or for forms that we don’t need to manipulate the input’s value.

Understanding Controlled and Uncontrolled components in React (6)

Here’s a screenshot for a clearer view.

Understanding Controlled and Uncontrolled components in React (7)

Uncover frustrations, understand bugs and fix slowdowns like never before with OpenReplay — an open-source session replay suite for developers. It can be self-hosted in minutes, giving you complete control over your customer data.

Happy debugging! Try using OpenReplay today.

When deciding which component to use, it’s essential to consider the pros and cons of controlled and uncontrolled components.

Controlled components are beneficial because they make managing and tracking the component’s state easy. They also allow you to validate the input before updating the state, enabling you to update the state based on the value of multiple elements. However, they can be more complex and unsuitable for specific use cases, such as when accessing the DOM element directly.

Uncontrolled components are beneficial because they are simpler to implement and allow you to access the DOM element directly. They also allow you to set the initial value of the element without having to manage the state. However, they can be less flexible and more challenging to track and manage the component’s state.

Here are some pros and cons of using controlled and uncontrolled components in React:

Pros of controlled components:

  • Predictable state management: Since the parent component manages the component’s state, it is easy to predict it at any given time.
  • Centralized state management: All the state of the component is stored in a single location in the parent component, which makes it easy to manage and debug.
  • Easier to test: Since the component’s state is predictable, writing test cases for controlled components is more effortless.

Cons of controlled components:

  • Increased complexity: Controlled components can be more complex to set up and manage since the state needs to be passed down from the parent to child components.
  • More code: Controlled components can require more code than uncontrolled ones, making the codebase larger and more challenging to maintain.
  • Slower performance: Since the parent component manages the state of the component, additional render cycles may impact performance.

Pros of uncontrolled components:

  • Simplicity: Uncontrolled components are simpler to set up and manage since they manage their state internally.
  • Less code: Uncontrolled components require less code than controlled components, making the codebase smaller and easier to maintain.
  • Better performance: Since uncontrolled components manage their internal state, fewer render cycles can improve performance.

Cons of uncontrolled components:

  • Harder to predict state: Since the component’s state is managed internally, it can be harder to predict the state at any given time.
  • No centralized state management: The component’s state is spread across multiple locations in the code, making it harder to manage and debug.
  • More challenging test: Since the component’s state is harder to predict, writing test cases for uncontrolled components can be harder.

In general, controlled components are more suitable for forms and input elements. In contrast, uncontrolled components are ideal for elements that don’t require tracking the state, such as checkboxes and selects.

(Video) Controlled vs Uncontrolled Component | Part #30 | React js in Hindi tutorial

However, it’s important to consider your application’s specific requirements when deciding which component to use. For example, a controlled component may be a better choice if you need to validate the input or update the state based on the value of multiple elements. An uncontrolled component may be better if you need to access the DOM element directly.

In this article, we’ve discussed the differences between controlled and uncontrolled components in React. Controlled components have their state and behavior controlled by React, while uncontrolled components have their state and behavior controlled by the DOM.

When deciding which type of component to use, it’s important to consider the specific requirements of your application. Controlled components are more suitable for forms and input elements, while uncontrolled components are more suitable for elements that don’t require tracking the state, such as checkboxes and selects.

FAQs

What do you know about controlled and uncontrolled components React? ›

In React, controlled components refer to components that have their state and behavior controlled by the parent component. These components rely on props passed down from the parent component to update their state and behavior. Uncontrolled components refer to components that manage their own state internally.

What is controlled and uncontrolled components in React with examples? ›

Difference Table Between Controlled and Uncontrolled Component
Controlled componentUncontrolled component
It stores the current value in the form of props.It stores the current value using react ref.
It has better control over the form data.It has limited control over the form data.
4 more rows
Feb 26, 2023

Should I use controlled or uncontrolled components? ›

In most cases, we recommend using controlled components to implement forms. In a controlled component, form data is handled by a React component. The alternative is uncontrolled components, where form data is handled by the DOM itself.

How do you handle controlled component element data in React? ›

In React, there are two ways to handle form data in our components. The first way is by using the state within the component to handle the form data. This is called a controlled component. The second way is to let the DOM handle the form data by itself in the component.

Can a component be both controlled and uncontrolled? ›

To make a hybrid component that can support being both controlled and uncontrolled, we need to make the props that control it optional.

Who handles uncontrolled component? ›

In a controlled component, form data is handled by a React component. Whereas in uncontrolled components, form data is handled by the DOM itself. Usage of Component State is a must for controlled components.

What is lazy loading in React? ›

In simple terms, lazy loading is a design pattern. It allows you to load parts of your application on-demand to reduce the initial load time. For example, you can initially load the components and modules related to user login and registration. Then, you can load the rest of the components based on user navigation.

What are two ways data gets handled in React? ›

What are the two ways that data gets handled in React? Answer : state & props.

Why use uncontrolled components React? ›

Uncontrolled components are generally used when the use case is simple or the action is not trackable; for example, a user uploading a file using file input. The basic requirement of any uncontrolled component is to be handled by the DOM. In this case, we cannot pass the state variable inside the form's input element.

What are hooks in React? ›

React Hooks are simple JavaScript functions that we can use to isolate the reusable part from a functional component. Hooks can be stateful and can manage side-effects. React provides a bunch of standard in-built hooks: useState : To manage states. Returns a stateful value and an updater function to update it.

What are the lifecycle methods of React? ›

The three phases are: Mounting, Updating, and Unmounting.

What is JSX Babel and Webpack? ›

What Are Webpack and Babel? Webpack and Babel are tools for developers that optimize JavaScript applications. Webpack is a module bundler we can use to minify multiple files in a JavaScript project and increase the overall efficiency. A module bundler takes in all the assets and comes up with a single output file.

How many elements can a valid React component return? ›

In react component, we can return only one element.

How do you handle lifecycle method in functional component? ›

A React component undergoes three different phases in its lifecycle, including mounting, updating, and unmounting. Each phase has specific methods responsible for a particular stage in a component's lifecycle. These methods are technically particular to class-based components and not intended for functional components.

Why is a router required in React? ›

The primary goal of Router in React JS is to supply the browser with an asynchronous URL that corresponds to the data that will show on the web page. It is mainly used to create single-page web apps since it retains the application's regular structure and functionality.

What is the difference between controlled and uncontrolled variables? ›

If you don't control relevant variables, you may not be able to demonstrate that they didn't influence your results. Uncontrolled variables are alternative explanations for your results and affect the reliability of your arguments.

What is the difference between controlled and uncontrolled environment? ›

A controlled environment is one where we control the variables: we “run the clock,” the location/ duration of a drill, or the intensity of conditioning. In an uncontrolled environment there is an enemy out there trying to kill us, figuratively or literally (military combat operations).

What is the difference between default value and value in React? ›

The difference between the defaultValue and value property, is that defaultValue contains the default value, while value contains the current value after some changes have been made. If there are no changes, defaultValue and value is the same (see "More Examples" below).

Why do we use useRef in React? ›

The useRef Hook allows you to persist values between renders. It can be used to store a mutable value that does not cause a re-render when updated. It can be used to access a DOM element directly.

Can we create custom hooks in React? ›

How do you make a custom hook in React? A custom React JS hook is created by using the 'use' prefix. For eg, a custom hook can be named 'useLocalStorage' or 'useBoolean'. A custom hook will consist of one or more React JS hooks from the library.

What is a virtual DOM in React? ›

The virtual DOM provides a mechanism that abstracts manual DOM manipulations away from the developer, helping us to write more predictable code. It does so by comparing two render trees to determine exactly what has changed, only updating what is necessary on the actual DOM. Like React, Vue also employs this strategy.

Can I use suspense without lazy? ›

React lazy loading can not do without the Suspense component, which also can not work with a fallback prop because we will still get the same error even if we don't specify a Suspense component. However, there's no problem in programming that does not have a solution.

How do you load images faster in React? ›

To load images faster in a React application you can use one of the following techniques: Use lazy loading method --> The image loads only when the user scrolls to it. Use blur technique --> This loads the images in low resolution initially before the original load.

What is fallback in React? ›

What is a React Fallback UI? A React fallback UI is a component rendered when an error occurs within React component tree or when a component is suspended due to a network request for data that is asynchronous.

How do you communicate between two components in Reactjs? ›

As stated in the React documentation: For communication between two components that don't have a parent-child relationship, you can set up your own global event system. Subscribe to events in componentDidMount(), unsubscribe in componentWillUnmount(), and call setState() when you receive an event.

What is the best way to fetch data in React? ›

React uses the thrown value to detect if the component is ready to be rendered. Once data is fetched, you just need to throw the data, and the component will be rendered. This very simple and quick method allows you to tell React that you want it to handle data fetching status instead of handling it yourself.

How do I fetch API in React? ›

See the below steps to implement and use Fetch API to fetch the data in a react app.
  1. Create a react application. ...
  2. Change your project directory. ...
  3. Access the API endpoint. ...
  4. Import the useState() hook and set to hold data. ...
  5. Create a FetchInfo() callback function to fetch and store data. ...
  6. Output. ...
  7. Create a react application.
Dec 19, 2022

Does every React component need a key? ›

Here's the rule: Whenever you're rendering an array of React elements, each one must have a unique key prop.

How do you pass data to a child component? ›

The most basic and commonly used way to pass data from a parent component to a child component is through props. Props, short for properties, are read-only values that are passed from a parent component to a child component.

Is it better to use functional or class components React? ›

Nothing is better, because both have pros and cons. But class components are important to understand React flow and lifecycle methods. The new learner should practice React using class components. Once they are familiar with class components, they can learn and use functional components.

Why do we use useEffect in React? ›

The useEffect Hook allows you to perform side effects in your components. Some examples of side effects are: fetching data, directly updating the DOM, and timers. useEffect accepts two arguments. The second argument is optional.

What is the difference between useEffect and useState? ›

The useState hook is used for storing variables that are part of your application's state and will change as the user interacts with your website. The useEffect hook allows components to react to lifecycle events such as mounting to the DOM, re-rendering, and unmounting.

What is the difference between Hooks and class components? ›

The major difference between Hooks and class-based state is that hooks are used inside of the functional component. One thing to keep in mind is that never call hooks inside of a any logic, it should always be on the top level! useState() is a hook that allows you to play with state in functional components in react.

What is the difference between hooks and lifecycle methods? ›

What is the difference between React hooks and lifecycle methods? React hooks provide a more concise way to manage state and side effects in functional components. Lifecycle methods are only available in class components and can hook into various stages of a component's lifecycle.

What is the smallest building block of ReactJS? ›

Elements are the smallest building blocks of React apps. An element describes what you want to see on the screen: const element = <h1>Hello, world</h1>; Unlike browser DOM elements, React elements are plain objects, and are cheap to create.

What is render in React? ›

In React, Render is the technique that can redirect a page with the help of function render(). Most importantly, render a function we can use to define the HTML code within the HTML element. It helps to display certain views in the UI using certain logic defined in the render function and returns the output.

What is the difference between props and state? ›

The difference comes in which component the data are owned. State is owned locally and the component itself updates it. Props are owned and read-only by a parent. Props can be changed only if an upstream shift is caused by a callback function passed on to the child.

What is the difference between XML and JSX? ›

The generated code runs faster than an equivalent code written directly in JavaScript. On the other hand, XML is detailed as "A simple, very flexible text format". A markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable.

What is npm for React? ›

NPM is short for node package manager, an online directory that contains the various already registered open-source packages. NPM modules consume the various functions as a third-party package when installed into an app using the NPM command npm install .

Can you have two returns in a function React? ›

Answer. Yes, you can return more than one element in the render function.

Is it possible to return more than one element in Reactjs? ›

Since v16. 0, React allows us to return multiple elements from the render function by wrapping them in an array. In previous versions, it was necessary to wrap multiple elements into a single parent, which resulted in an extra node appearing in the DOM tree.

Can I extend a React component? ›

Using the extends keyword, you can allow the current component to access all the component's properties, including the function, and trigger it from the child component. This example creates one component called ParentClass. jsx. ParentClass extends the component from React as React.

What are the three lifecycle methods? ›

Lifecycle Phases

There are three categories of lifecycle methods: mounting, updating, and unmounting.

Why Hooks are used instead of lifecycle methods? ›

State and Lifecycle methods are the backbones of any React application, and Hooks enable functional components to implement them efficiently. Hooks allow you to use state and other React features without writing a class as they do not function inside classes.

What happens if you attempt to update the state directly? ›

The state of a component is managed internally by React. Updating the state of a component directly can have unintended consequences that can be difficult to debug. If the state is updated directly as in the example above, the component will not rerender since the state is compared shallowly.

How many types of routing are there in React? ›

They are technically three different packages: React Router, React Router DOM, and React Router Native. The primary difference between them lies in their usage. React Router DOM is for web applications and React Router Native is for mobile applications made with React Native.

What is the difference between Link and route in React? ›

So in a nutshell, the Link component is responsible for the transition from state to state (page to page), while the Route component is responsible to act as a switch to display certain components based on route state.

What are controlled vs uncontrolled components and stateless vs stateful components? ›

A controlled component has its state controlled from outside. Because of this, controlled components are usually stateless as they do not store their own state and receive it from a parent component. Uncontrolled components are essentially stateful, as they store and maintain their own internal state.

What are uncontrolled components in React hooks? ›

Unlike controlled components, uncontrolled components are where form elements are directly accessed and handled by the DOM itself. React does not handle the input's value and has no way of controlling/updating its value. In order to access the element via the DOM, we use the useRef Hook.

What are controlled inputs in React? ›

The official documentation defines controlled inputs as: The React component that renders an element also controls what happens in that element on subsequent user input. An input form element whose value is controlled by React in this way is called a “controlled input.”

What is the difference between controlled and uncontrolled components in Vue? ›

Where controlled are components working within the react model, and state is tracked in the virtual dom. And uncontrolled are managed outside the virtual dom. Since Vue also works with a virtual dom is there a wrong way to grab elements (for instance can you use document.

What is the difference between controlled and uncontrolled React hook forms? ›

Controlled input vs Uncontrolled input

By using a controlled component, developers let React manage input values, with the help of a React state. By using an uncontrolled component, developers have to manually detect changes in the component with the help of React references.

How many types of Hooks are there in React? ›

React version 18 provides 15 hooks for developers. With 15 hooks, you achieve similar functionality to a class-based component. All hooks are provided by the React team. The most common hook is useState, and other hooks are used based on the app requirements.

What is the difference between Hooks and functional components in React? ›

The major difference between Hooks and class-based state is that hooks are used inside of the functional component. One thing to keep in mind is that never call hooks inside of a any logic, it should always be on the top level! useState() is a hook that allows you to play with state in functional components in react.

What is the difference between controlled and uncontrolled input? ›

Controlled component is component that get the changed value from the callback function and uncontrolled component is component that have the one from the DOM. For example, When input value is changed,we can use onChange function in Controlled Component and also we can get the value using DOM like ref.

Are hooks components a controlled component? ›

React offers 2 approaches to access the value of an input field: using a controlled or uncontrolled component techniques.

Videos

1. Why I avoid react's uncontrolled inputs
(Web Dev Cody)
2. Controlled and Uncontrolled Components in reactjs #shorts #reels #reactjs
(techbani)
3. React Tutorial: Handling Forms in React (Controlled & UnControlled Components)
(Varun Prashar)
4. React Native Tutorial 10: Uncontrolled v/S controlled components
(codedamn)
5. REACT JS - Controlled and Uncontrolled Components in React JS Made Easy!
(Four-T Code)
6. Controlled and Uncontrolled Components in React
(Umesh Ramya)
Top Articles
Latest Posts
Article information

Author: Terrell Hackett

Last Updated: 05/20/2023

Views: 6045

Rating: 4.1 / 5 (72 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Terrell Hackett

Birthday: 1992-03-17

Address: Suite 453 459 Gibson Squares, East Adriane, AK 71925-5692

Phone: +21811810803470

Job: Chief Representative

Hobby: Board games, Rock climbing, Ghost hunting, Origami, Kabaddi, Mushroom hunting, Gaming

Introduction: My name is Terrell Hackett, I am a gleaming, brainy, courageous, helpful, healthy, cooperative, graceful person who loves writing and wants to share my knowledge and understanding with you.