Controlled props are a fundamental concept in React that allows components to manage their own state through props passed down from parent components. This approach ensures that the component's behavior is predictable and that the state is synchronized with the UI. By using controlled props, developers can create more maintainable and testable code, as the component's state is always derived from its props.
In a controlled component, the parent component holds the state and passes it down to the child component as props. The child component then uses these props to render its UI and can also notify the parent of any changes through callback functions. This pattern is particularly useful for form elements, where the input values are controlled by the parent component.
Here’s a simple example demonstrating controlled props with a text input field:
import React, { useState } from 'react';
const ParentComponent = () => {
const [inputValue, setInputValue] = useState('');
const handleChange = (event) => {
setInputValue(event.target.value);
};
return (
<div>
<h1>Controlled Input Example</h1>
<ChildComponent value={inputValue} onChange={handleChange} />
<p>Current Value: {inputValue}</p>
</div>
);
};
const ChildComponent = ({ value, onChange }) => {
return (
<input type="text" value={value} onChange={onChange} />
);
};
export default ParentComponent;
In conclusion, controlled props are a powerful feature in React that enhance the way components communicate and manage state. By adhering to best practices and avoiding common pitfalls, developers can create robust and maintainable applications that provide a seamless user experience.