What is the difference between redux tool kit query and create asynx thunk?

Viewed 1262

I understand the how to use create async thunk and redux tool it query, if redux tool kit query solves pending, fulfilled, rejected and also catches the data then whats the use of create async thunk which main purpose is that and stores data in store.

2 Answers

cAT is a generalized building block, RTK Query is a specialized single purpose tool. RTK Query uses cAT internally, essentially as if you were doing that by hand - but with very few code.

It saves you dozens of lines of code per endpoint, provided caching api data is exactly what you want to do.

That said, I'm not 100% you really grasp both those tools and what they do for you. I'd recommend you go through chapters 5-8 of the official Redux tutorial as those will show you both those tools in-depth.

The most common use case for side effects in Redux apps is fetching data. Redux apps typically use a tool like thunks, sagas, or observables to make an AJAX request, and dispatch actions based on the results of the request. Reducers then listen for those actions to manage loading state and cache the fetched data.

RTK Query is purpose-built to solve the use case of data fetching. While it can't replace all of the situations where you'd use thunks or other side effects approaches, using RTK Query should eliminate the need for most of that hand-written side effects logic.

RTK Query is expected to cover a lot of overlapping behaviour that users may have previously used createAsyncThunk for, including caching purposes, and request lifecycle management (e.g. isUninitialized, isLoading, isError states).

In order to migrate data-fetching features from existing Redux tools to RTK Query, the appropriate endpoints should be added to an RTK Query API slice, and the previous feature code deleted. This generally will not include much common code kept between the two, as the tools work differently and one will replace the other. Read: [Learn More] [1] https://redux-toolkit.js.org/rtk-query/usage/migrating-to-rtk-query

Related