Separation of Concerns Between SearchInput and SearchList
Overview: A critical aspect of optimizing React applications is separating concerns between components. By isolating the input field and the search results, we can ensure that only the necessary component re-renders. The SearchInput
component handles the user input, while the SearchList
component is responsible for displaying the search results. This separation allows for more efficient rendering and easier maintenance.
Implementation: In this approach, the SearchInput
component is responsible for capturing the user’s search query and applying the debouncing logic. The debounced query is passed up to the SearchPage
component, which then passes it down to the SearchList
for displaying the results. This ensures that each component has a clear, focused responsibility.
function SearchInput({ onDebouncedQueryChange }) {
const [searchQuery, setSearchQuery] = useState("");
const handleInputChange = (e) => {
setSearchQuery(e.target.value);
};
useEffect(() => {
onDebouncedQueryChange(searchQuery);
}, [searchQuery, onDebouncedQueryChange]);
return (
<input
type="text"
value={searchQuery}
onChange={handleInputChange}
placeholder="Search..."
/>
);
}
function SearchList({ q }) {
const { data, isFetching } = useSearchSnipps(q);
return (
<div>
{isFetching ? <Spinner /> : data.map((item) => <FeedItem key={item.id} item={item} />)}
</div>
);
}
This structure ensures that the logic for capturing input and displaying results is handled separately, making the code easier to understand and maintain.
Comments