• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

Controlled vs Uncontrolled Components

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
In the React world, we have two types of components, which are controlled and uncontrolled components. We are going to explore how they differ fundamentally. Moreover, I will explain them with code examples so that one may want to improve their knowledge about controlled and uncontrolled components, and use them in real-life scenarios.

Controlled vs Uncontrolled Components

Firstly, let’s remember what we understand when we say React component.

Components are independent and reusable bits of code. They serve the same purpose as JavaScript functions, but work in isolation and return HTML. Components come in two types, Class components and Function components.

In the past, there were only class components in React, and if you wanted to write a component, there was no other option. A React class component is simply a JavaScript class that contains state methods, etc. Afterwards, people who made React decided to write functional components due to their simplicity, easy readability, easy testability, and performance, and functional components are said to be more easily tested.

When we write apps, most of the time, there will be forms and form data in these forms. And there are 2 main ways to handle form data and its logic.

One of them is controlled components. As the name implies, we have control over the variables since we store them in our state. In React, we manage the state in functional components with the useState hook. Let’s say we have a login form, we need to store the username and password in our state and control the data we store in our form and submit or make other operations respectively.


import React, { useState } from 'react';

function ControlledInput() {
const [value, setValue] = useState('');

const handleChange = (e) => setValue(e.target.value);

return (
<div>
<h3>Controlled Input</h3>
<input type="text" value={value} onChange={handleChange} />
<p>Value: {value}</p>
</div>
);
}

As you see in the code, we have a component named ControlledInput and a value state. We give input element onChange functionality and give the function handleChange. It takes what’s inside the input field and sets it to the value state. This is an example of how to manage input fields using controlled components.

What advantage do we have here is the important point. The key points are:

1- We managed the state using useState, the input value is bound to React state.

2- The input always updates via onChange.

3- Since we have control over the value, one may easily validate or manipulate the data.

We used one input field, however, there could be many inputs. The number of inputs is up to you.

In the uncontrolled components, we manage the data in the forms using Javascript DOM internally. Though it is not recommended to directly manipulate the DOM, we may interact with the data with the useRef hook. Let’s say again, we have value, we may interact with it through this.valueRef using useRef hook. Don’t forget to use useRef, do not manipulate the DOM directly, otherwise there is no point in using React.

We have the value inside the value state we need to use this.valueRef.current.value, in this way we may interact with the value inside the state and submit them accordingly. In this way, you get the current state of the value and send it to your server.

Uncontrolled components may be faster and easier to implement. If you have less data and when you do not need any validation or data manipulation, one may easily implement the uncontrolled component, and provides simple form data logic. Uncontrolled components are simple and straightforward, easy to setup and directly interacts with the DOM. If you have a case like this do not be discouraged to use them.

Here is a code example for uncontrolled components and how they handle the form data.


import React, { useRef } from 'react';

function UncontrolledInput() {
const inputRef = useRef();

const handleSubmit = () => {
alert('Input value: ' + inputRef.current.value);
};

return (
<div>
<h3>Uncontrolled Input</h3>
<input type="text" ref={inputRef} />
<button onClick={handleSubmit}>Submit</button>
</div>
);
}

As you may see, we created the inputRef variable using useRef hook. Afterwards, we give ref property to our input tag and give the value inputRef. Then, using the handleSubmit function, we may be able to send the data to the server or wherever we want. The main point here, you should not use inputRef when you try to reach the value of the input, use inputRef.current.value instead.

Most likely you would not need to use both of them in the same component, however, for explaining purposes I added the below code example so that you would see directly how their usage differs and what it looks like:


import React, { useState, useRef } from 'react';

export default function ControlledVsUncontrolled() {
// Controlled form state
const [controlledForm, setControlledForm] = useState({
name: '',
email: '',
password: '',
});

// Uncontrolled form refs
const nameRef = useRef();
const emailRef = useRef();
const passwordRef = useRef();

// Controlled handlers
const handleControlledChange = (e) => {
const { name, value } = e.target;
setControlledForm((prev) => ({ ...prev, [name]: value }));
};

const handleControlledSubmit = (e) => {
e.preventDefault();
alert('Controlled Form:\n' + JSON.stringify(controlledForm, null, 2));
};

const handleUncontrolledSubmit = (e) => {
e.preventDefault();
alert('Uncontrolled Form:\n' + JSON.stringify({
name: nameRef.current.value,
email: emailRef.current.value,
password: passwordRef.current.value
}, null, 2));
};

return (
<div style={{ display: 'flex', gap: '40px' }}>
{/* Controlled Form */}
<form onSubmit={handleControlledSubmit}>
<h2>Controlled Form</h2>
<div>
<label>Name:</label>
<input
name="name"
value={controlledForm.name}
onChange={handleControlledChange}
/>
</div>
<div>
<label>Email:</label>
<input
name="email"
type="email"
value={controlledForm.email}
onChange={handleControlledChange}
/>
</div>
<div>
<label>Password:</label>
<input
name="password"
type="password"
value={controlledForm.password}
onChange={handleControlledChange}
/>
</div>
<button type="submit">Submit Controlled</button>
</form>

{/* Uncontrolled Form */}
<form onSubmit={handleUncontrolledSubmit}>
<h2>Uncontrolled Form</h2>
<div>
<label>Name:</label>
<input name="name" ref={nameRef} />
</div>
<div>
<label>Email:</label>
<input name="email" type="email" ref={emailRef} />
</div>
<div>
<label>Password:</label>
<input name="password" type="password" ref={passwordRef} />
</div>
<button type="submit">Submit Uncontrolled</button>
</form>
</div>
);
}

Both of the forms have the same functionality, just the usage is different.

When to choose controlled components, and when to choose uncontrolled components?

If you need validation and manipulation, most likely you would like to choose controlled components since it is easier to implement for validation logic, and with the directly updated state, you have more control compared to uncontrolled components. You may add Formik and Yup to controlled components and make validation simpler, and you would have access to yup validators directly. Rather than implement your own email logic, you would have a direct email validator inside the library and use it accordingly.

However, if you need the interact directly with the DOM and you need a quick form without validation or other features, the uncontrolled component is a way to go. If you have a simple complexity in your form and you want direct DOM interaction, use an uncontrolled component, and you can quickly implement a nice form. Complexity of the form is one of the aspects you should consider while choosing controlled vs uncontrolled components.

Let’s say you have a newsletter registration form and you need only email input, uncontrolled components is very much likely satisfy your requirements. You do not need live validations or complex form validation logic in this case, therefore, it would be logical to use uncontrolled components.

Moreover, if one wants to avoid re-renders and performance is a key criterion in the form, uncontrolled components would be more beneficial since there would be no state updates every time you clicked or typed something.

You would need an uncontrolled component if you have different input data types like file, charts or maps again.

In conclusion, at the end of the day, you are responsible for what type of component you choose for your form logic. There are many things to consider, like ease of maintenance, simplicity, performance, and complexity of the forms. Hope you get the main idea between the different types of form component handling logic. Thank you for reading this far.


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.




Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу