Stop Making API Requests in Redux Action-Creators

Joseph Olabisi
The Startup
Published in
2 min readJan 25, 2021

Disclaimer: The views and opinions expressed here may not necessarily reflect best practices

Photo by Diego PH on Unsplash

Context

We write a lot of code for simple API calls. Getting data from an API in react/react-native applications usually involves some convoluted number of steps; usually, we have three states of the action (initialization/request, success, failed). This leads to three different action-creators and reducers.

Which follows these steps:

Action-Initiated — Initiates API request; update store via reducer.

Action-Success — Do something with the result if request is a success, then dispatch an action. Reducer updates the redux-store.

Action-Failed — Do something with the result of request if it failed, then dispatch an action. Reducer updates the redux store.

Then our component listens to the store, probably using the useSelector hook.

From the steps, we explicitly create three different redux action-creators and three reducers. This is quite verbose.

Another problem with this approach is the overuse of the redux store. Every simple API request requires an update of the redux store for the loading state and data. In most cases, the data is not shared amongst several components; hence unnecessary dependence on the redux store.

Solution

So whats the alternative?

  1. Make API request in a specific component.
  2. Update the component with the data gotten from the API response.
  3. Dispatch an action that updates the store with the data if it needs to be used across components.

The above works great; but it causes our component to be less flexible, no separation of concern, and most likely a lot of repeated logic.

So to solve this we could write a simple re-usable hook for fetching data.

Works great! However, we might need some added functionalities like caching, deduping multiple requests for the same data, pagination, lazy loading, etc.

This brings us to powerful libraries for data fetching like React-Query and SWR.

Lets us look at an example with React-Query.

Moving useQuery out of CustomComponent and into a custom hook, keeps our component abstracted allowing more flexibility and reusability.

Conclusion

Here I describe my personal opinion on data fetching in react/react-native applications. I explain why data fetching should be limited to components and not redux action-creators.

There might still be scenarios where this approach might not play out well. Fetching data in redux action-creators might be the best option.

Let me know what you think about this approach in the comments.

Happy Coding!

--

--