~2 min read • Updated Oct 24, 2025
Introduction
In the previous version of the application, every keystroke in the search field triggered a new API request. This behavior can lead to rate limiting and unnecessary network traffic. To prevent this, we implement explicit data fetching — data is only fetched when the user clicks a confirmation button.
Adding a Confirmation Button
First, we add a new button that triggers the search request:
<button
type="button"
disabled={!searchTerm}
onClick={handleSearchSubmit}
>
Submit
</button>Defining Two Separate States
We use two states: one for the current input value (searchTerm) and another for the confirmed value that triggers the API request (url):
const [searchTerm, setSearchTerm] = useStorageState('search', 'React');
const [url, setUrl] = React.useState(`${API_ENDPOINT}${searchTerm}`);
const handleSearchInput = (event) => {
setSearchTerm(event.target.value);
};
const handleSearchSubmit = () => {
setUrl(`${API_ENDPOINT}${searchTerm}`);
};Fetching Data with useCallback and useEffect
We define the data-fetching function using useCallback so it only runs when url changes:
const handleFetchStories = React.useCallback(() => {
dispatchStories({ type: 'STORIES_FETCH_INIT' });
fetch(url)
.then((response) => response.json())
.then((result) => {
dispatchStories({
type: 'STORIES_FETCH_SUCCESS',
payload: result.hits,
});
})
.catch(() =>
dispatchStories({ type: 'STORIES_FETCH_FAILURE' })
);
}, [url]);
React.useEffect(() => {
handleFetchStories();
}, [handleFetchStories]);Benefits of Explicit Fetching
- Prevents excessive API requests during typing
- Reduces risk of rate limiting and improves performance
- Gives full control over when data is fetched
- Prepares the app for future enhancements like debouncing or throttling
Conclusion
With explicit data fetching in React, API requests are only triggered when the user confirms their search. This approach improves stability, reduces unnecessary network calls, and enhances the overall user experience.
Written & researched by Dr. Shahin Siami