React - Fetch from external API function on button click
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.
Introduction
Button driven API calls are a common React pattern for search tools, admin actions, and on demand reports. The key is to keep network state explicit so loading, success, and error behaviors remain predictable. A robust implementation also handles repeated clicks, cancellation, and stale response ordering.
Build a Clear State Model First
When a request starts on click, track at least four pieces of state:
- current status
- response data
- user facing error message
- last request identifier
You can model this with useState, or with useReducer if the flow grows. For many screens, useState is enough.
This pattern is readable and handles normal failure conditions cleanly.
Prevent Stale Responses During Rapid Clicks
If users can trigger new requests quickly, a slower old response may arrive after a newer request and overwrite correct data. Solve this with cancellation and request identity.
Cancellation keeps UI aligned with the latest user intent.
Move API Calls Out of the Component
As screens grow, keep component code focused on rendering and state transitions. Put HTTP logic in a small API module.
Then import this function inside your component. That makes unit tests easier and reduces duplication across pages.
Decide UI Behavior for Existing Data
One design decision matters: do you clear old data on every click, or keep old data until the new request succeeds.
Good default for dashboards:
- keep previous data visible
- show loading state on top
- replace data only after success
Good default for destructive operations:
- clear old result immediately
- display explicit pending state
- show strong error if request fails
Pick one behavior intentionally so the interface feels consistent.
Testing the Click to Fetch Flow
Use React Testing Library and mock fetch to verify state transitions.
This protects against regressions when refactoring event handlers.
Common Pitfalls
A common mistake is treating only thrown network errors as failures and ignoring non success HTTP status codes. Always check response.ok.
Another issue is allowing overlapping requests without cancellation. Users then see results from older clicks and lose trust in the interface.
Teams also place all fetching logic inline in components, which makes code hard to test and harder to reuse.
Summary
- Trigger button based fetches through explicit state transitions.
- Track loading, success, and error states independently.
- Prevent stale updates with
AbortControllerwhen clicks can overlap. - Extract API logic into separate modules as complexity grows.
- Test the click flow so refactors do not break user visible behavior.
Related reading
- Read asynchronously data from NetworkStream with huge amount of packets
- read kafka message starting from a specific offset using high level API
- Reading streaming http response with Python requests library
- Read/Write String from/to a File in Android
- React dispatch a method in async call
- React HOC pattern - dealing with async methods
- (Re)attaching to an App Insights Operation from another machine/process (not using HTTP)
- Receive AccessDenied when trying to access a page via the full url on my website

System Design Fundamentals
Build a strong foundation in designing scalable, reliable distributed systems.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.