Search code examples
reactjsreduxredux-thunkredux-toolkitrtk-query

Redux Toolkit: What is the Preferred Method for Data Fetching?


I'm currently using React (with hooks) and Redux-Toolkit. After reading through the docs, I've come across Redux Thunks, createAsyncThunk, and RTK Query. Out of these three methods, which is the best for fetching data in a Redux slice, modifying that data within the slice, and then dispatching said data to a React?

Thanks in advance for your answers!


Solution

  • Each of them serves its own purpose, and only RTK-Q is made exactly for data fetching and caching.

    The "problem" is that it's

    1. Not really integrated with the application store's Redux and Thunks by default - it "lives" in its own store, with its own cache state, actions, and middleware.

    The idea is that you don't want to put fetched data in your app-store, course, it will just duplicate the data and add another "source of truth" with the following inconsistency.

    RKT-Q adds a concept of "API state", which represents the data on the backend, and should be handled significantly differently than App's (frontend) state.

    In extra cases, you may handle the RTK-Q-related actions, handle them in your middleware (Thunks in your case) and update your Redux app-state producing actions with some calculated data\flags, etc.

    1. Not covering all the cases of Application <-> API negotiation.

    As an example - file\data export, API action calls, and other stuff that is out of RESTfull architecture. If you'll try to download a file from API via RTK-Q you'll find how bad it's covering such a case, and you'll be forced to use separate flow via Thunks\Sagas or\with plain fetch API to do so.

    But still, RTK-Q brings you so much out of the box, so it is worth using it by default for data fetching, even with some work to handle several edge cases.

    Wrapping up - I believe that there is no right\complete answer to your question and just more things to consider for your own app architecture design.