How to fetch data with React-Concurrent

Hossein Mohammadi
2 min readNov 3, 2020
React-Concurrent fetching data

Most applications use server-side APIs, developers need to fetch data or send data to servers, they're doing some stuff in the front side like showing loading to user until service response received, showing error if the service gives an error, showing data to the user, or some other things like recalling API. They code all of them again and again where they need it. So the Question is, Is there a better solution? We will talk about it in this story.

React saved our lives by introducing hooks. Its most important advantage is the ability to share between components. With react hooks we can move our state management to a custom hook and use them elsewhere. It is amazing and so hard to do without hooks.

Fetching with hooks

I am showing you the code of the common way that developers use to fetch.

In this code, we're fetching a list from an API that takes a query parameter. Once the query is changed, the list will be fetching again.
If we want to add loading and error, this code will be like this:

This code is so cool, but there are mistakes because there is so much code. You couldn’t code this everywhere. The best way is to change it to a costume hook and use it everywhere. You can do it yourself or use tools already developed.

Our Suggestion

React-Concurrent is a tool for fetching data easily.

We can write the above example with React-Concurrent in this way

This tool can reduce your mistakes and improve your developer experience, if you work with a team you have a pattern for fetching data and every one has used it so codes are so readable. This tool is so powerful under the hood you can use it outside of components, or combine it with React.Context. If you have questions or issues, open an issue on GitHub. Or if you have any idea you are so welcome please open an issue or PR.

--

--