Fetching data in React using XMLHttpRequest and Fetch API is fine but require a lot of boilerplate codes. Using a data fetching library is preferred as following solutions will simplify the logic of data fetching in your project with tons of amazing built-in features.
- Axios - A promise-based isomorphic HTTP client which can run in the browser and NodeJS with the same codebase. On the server-side it uses the native NodeJS http module, while on the browser it uses XMLHttpRequests.
- Relay - The production-ready GraphQL client for React, developed by Facebook, was designed to be performant from the ground up, built upon locally declaring data dependencies for components.
- SWR - A React Hooks library for data fetching, created by Next.js team, lightweight, and backend agnostic.
- React Query - A library handles fetching, caching, background updates and stale data out of the box with zero-configuration. It is backend agnostic so you can use React Query with literally any asynchronous data fetching client.
- React Async - A utility belt consists of a React component and several hooks for declarative promise resolution and data fetching, easy to handle asynchronous UI states without assumptions about the shape of your data or the type of request.
- Transport and protocol agnostic (REST, GraphQL, etc)
- Caching, refetching, polling, realtime
- Pagination, load more, infinite scrolling
- Requests and responses interception
- Revalidation on focus, network recovery
- Performance optimizations
- Request cancellation