This content originally appeared on Bits and Pieces - Medium and was authored by Piumi Liyana Gunawardhana
Using React Async to Handle Asynchronous UI States in React Applications
With JavaScript, we typically use async/await for asynchronous operations like data fetching. The same remains even if we use UI libraries like React. But, what if you get a React component and a Hook to fetch data instead?
React Async exactly does that by providing a component-driven approach to fetch data from an API. In this article, I will discuss its core features to give you a better understanding.
Introduction to React-Async
React Async is a promise-based library that offers a declarative API to make API calls. It provides a React component and a Hook for declarative promise resolution and data fetching.
React Async is compatible with almost all the data fetching libraries and APIs, including Fetch API, Axios, and GraphQL. Also, it works well with React Native too.
Installing React Async
Installing React Async is pretty straightforward. You can treat it like any other JavaScript library and install it using NPM or Yarn.
//NPM
npm install — save react-async
//Yarn
yarn add react-async
It has more than 33K weekly downloads and 2K GitHub stars.
Note: Please keep in mind to install React as a peer dependency for this package. You’ll need react@16.8.0 or later if you wish to use the useAsync hook.
Basics of React Async
React Async is a simple library. To get things started, you need to get familiar with its three main APIs:
1. <Async> component.
2. useAsync hook.
3. createInstance factory function.
So, let’s see what those APIs are and their usage in detail.
1. As a Component — <Async>
Async component is the classic interface of React Async, and we can use it to make React components more declarative. Here, we can directly use the <Async> component in JSX to apply the render props pattern.
Following is a simple example of using <Async> component to fetch data.
In the above example fetch API is used to perform the API call inside the loadUsers function. It returns a Promise. And we can access the props, from the Promise parameters it returns.
The props are as follows:
- data: Requested data from the server.
- error: For instances where an error occurs.
- isLoading: For scenarios where the server response is still in progress.
With React Async, we don’t need to exploit classes or lifecycle methods to fetch data and no need to specify how to handle the data.
2. As a Hook — useAsync
The useAsync Hook allows you to use React Async basic functionalities directly in functional components.
If you are fond of using React Hooks, you can use the useAsync Hook instead of <Async> component. The below example shows how we can use the useAsync Hook to fetch data.
As you can see, I have passed the data fetching method loadUsers to useAsync Hook. And you can access the result, errors, or status using the props.
The library also offers another Hook called useFetch dedicated to use with Fetch API.
3. As a Factory Function — createInstance()
React Async offers a factory function called createInstance() . It allows you to design your component instances with options like default onResolveand onRejectcallbacks.
The below example, shows how we can create a custom instance of the Asynccomponent using createInstance().
By default, createInstance() accepts two input parameters, defaultOptionsand the displayName. In the above example, I have passed;
- loadUsers function — The defaultOption.
- AsyncUser— The instance’s display name.
Helper Components in React Async
Apart from the Async component, React Async provides several helper components to make JSX more declarative and clutter-free.
These Helper components can take a React element or a function as children and enable or disable rendering based on the current state. We can pass the current state to useAsync, or <Async> by using the Context.
Here is an example of how to use useAsync with the helpers. It is pretty much similar to using props.
In the above example, I have used three helper components:
- <IfPending> — Renders only while the Promise is pending (loading / unsettled).
- <IfRejected> — Renders only when the Promise is rejected.
- <IfFulfilled> — Renders only when the Promise is fulfilled (resolved to a value, could be undefined).
Helper components can increase the readability of your render functions by eliminating the need to write conditional returns.
Additional Features of React Async
React Async has a special DevTools package that facilitates debugging and development of asynchronous application states.
You can install it using NPM or Yarn with the following commands:
//NPM
npm install --save react-async-devtools
//Yarn
yarn add react-async-devtools
After installation, you need to import it and render the <DevTools/> component in your app root like this.
Apart from that, React Async offers plenty of configuration options to handle special scenarios.
These configurations can be sent as props to <Async {…options}> and custom instances, or as an object to useAsync(options).
Some of the most used configurations options are:
- promise - An already started Promise instance.
- promiseFn- A function that returns a Promise that is automatically invoked.
- initialValue - Provide initial data or errors for server-side rendering.
- onResolve - A callback invoked when Promise resolves.
- onReject - A callback invoked when Promise rejects.
- onCancel - A callback invoked when a Promise is canceled.
Build with independent components for speed and scale
Instead of building monolithic apps, build independent components first and compose them into features and applications. It makes development faster and helps teams build more consistent and scalable applications.
Bit offers a great developer experience for building independent components and composing applications. Many teams start by building their Design Systems or Micro Frontends, through independent components.
Give it a try →
Final Thoughts
In this article, I discussed how to use React Async library for declarative data fetching. It aims to resolve data as close as possible to where they will be consumed, just using declarative syntax and native promises.
React Async performs effectively even in complex applications with extensive nested data dependencies. It promotes loading data at the component level on-demand in parallel rather than loading bulks at a higher route or page levels.
Further, it would be ideal for large applications with a dynamic routing model or no routes since it’s completely independent of your routes.
So, I invite you all to use declarative data fetching with React Async in your next React project and share your thoughts in the comments section.
Thank you for reading..!!
Learn More
- Things You Should Know When Fetching Data for React Components
- React Error Handling and Logging Best Practices
- Introduction to Remotion — Create Videos and Animations with React
Declarative Data Fetching with React Async was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.
This content originally appeared on Bits and Pieces - Medium and was authored by Piumi Liyana Gunawardhana
Piumi Liyana Gunawardhana | Sciencx (2021-12-02T15:10:45+00:00) Declarative Data Fetching with React Async. Retrieved from https://www.scien.cx/2021/12/02/declarative-data-fetching-with-react-async/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.