Middle+
Tell about working with forms in React: controlled and uncontrolled components, pros and cons of each approach.
sobes.tech AI
Answer from AI
In React, forms can be implemented in two main ways: controlled and uncontrolled components.
Controlled components are when the form's state (field values) is stored in React's state (for example, in useState). Each change to a field triggers a state update, and the field's value is taken from this state.
Pros:
- Full control over the form and its validation.
- Easy to implement dynamic behavior and complex logic.
- The form's state is accessible in React, convenient for integration with other components.
Cons:
- More code and potentially slower with a large number of fields.
- Requires more effort for simple forms.
Uncontrolled components are when the field values are managed by the DOM itself, and React accesses them via refs.
Pros:
- Less code for simple forms.
- Faster with a large number of fields, as it does not update the state on each change.
Cons:
- Less control over the form.
- More difficult to implement complex validation and dynamic behavior.
Example of a controlled component:
import React, { useState } from 'react';
function ControlledForm() {
const [name, setName] = useState('');
const handleChange = (e) => setName(e.target.value);
const handleSubmit = (e) => {
e.preventDefault();
alert(`Name: ${name}`);
};
return (
<form onSubmit={handleSubmit}>
<input type="text" value={name} onChange={handleChange} />
<button type="submit">Submit</button>
</form>
);
}
The choice of approach depends on the complexity of the form and the requirements for state management.