HTML elements like <input> have internal state that isn’t automatically synced with React. To fully control their behavior, we turn them into controlled components, where React state manages their value and updates.
To control an input field, we bind its value to a state variable and update it via onChange:
const App = () => {
const [searchTerm, setSearchTerm] = React.useState('React');
const handleSearch = (event) => {
setSearchTerm(event.target.value);
};
return (
);
};
const Search = ({ search, onSearch }) => (
);Now the input field is fully controlled by React state, and every change triggers a re-render.
Props in React are passed as objects. To access their values more cleanly, we use object destructuring:
const Search = ({ search, onSearch }) => (
);This improves readability and reduces repetition.
When props contain nested objects, we can destructure them directly in the function signature:
const Item = ({
item: {
title,
url,
author,
num_comments,
points,
},
}) => (
{title}
{author}
{num_comments}
{points}
);This technique is useful when you only need specific properties from a nested object.
Controlled components in React allow precise control over form behavior. Using advanced props techniques like destructuring helps write cleaner, more maintainable code. These patterns are essential for building dynamic, reliable user interfaces in React.