What's the difference between Redux Toolkit Query vs. Redux Toolkit - reactjs

What can Redux Toolkit do, or do well in that RTK Query can't? I know that RTQ Query makes it easier to perform data fetching and caching with less code, but why do some projects that has Node.js and MongoDB as backend uses createAsyncThunk() from Redux Toolkit instead of createApi() from RTQ Query?

They are totally different things.
RTK Query is an optional addon included in the Redux Toolkit package. There are also alternative packages such as react-query, swr, See Comparison | React Query vs SWR vs Apollo vs RTK Query vs React Router. I think the RTK Query Overview documentation is clear enough.
Why do people(including me) use createAsyncThunk() in their projects may be because RTK Query has a learning cost and they want to keep their project simple and don't want to include too many packages and conceptions.
I write the logic about the data fetching and caching by myself instead of RTK query
RTK provides some APIs to help people address three common concerns about Redux:
"Configuring a Redux store is too complicated"
"I have to add a lot of packages to get Redux to do anything useful"
"Redux requires too much boilerplate code"
In particular, RTK uses immer underly, which greatly reduces the complexity of updating complex states and returning new references.

Internally, createApi will call the Redux Toolkit createSlice API to
generate a slice reducer and corresponding action creators with the
appropriate logic for caching fetched data. It also automatically
generates a custom Redux middleware that manages subscription counts
and cache lifetimes.
with createApi we create an api (this is not a backend code) and we get hooks (it also returns slice and thunks) from that api. Hooks automate the data fetching process. Basically, an api talks to one server so keeping all fetching logic in one function will keep your app neat. (But we need to do alot of configuration) All the endpoints will be in one spot so you see everything in one look. (compare it to node.js api logic, creating controllers in different files, how hard it is keep tracking of api requests) The communication (automated refetching, invalidating cache) between those fetchers is perfectly done under createApi.
with react toolkit query we are not only handling state management but also handling data fetching and caching, efficiently. If two components on a single page are making a network call to the same endpoint defined in RTK Query, it detects that and makes one single call instead. On the other hand, Redux toolkit is the same as react-redux but the only difference is redux toolkit (with using immer.js behind the scene) makes it write the same logic shorter and more secure.
Basically, react toolkit query is built on top of the redux toolkit. The logic is defining the data fetching first and then generating all the slice logic, reducers, middlewares, isLoading state based on those data fetching functions.
Comparison | React Query vs SWR vs Apollo vs RTK Query vs React Router
this link will show all the properties of the RTK Query

Related

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!
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
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.
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.

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

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.
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

What is the main difference between React Query and Redux?

currently I am using redux in different projects for state management. A few days back, I listened about react-query which is also used for state management and provides caching and async fetching. I am trying to figure out the main difference between these two libraries.
Where I should use react-query and in which cases I need redux.
React-query is what you would call a specialized library. It holds an api cache for you - nothing else. And since it is specialized, it does that job quite well and requires less code.
Redux on the other hand gives you tools to just about store anything - but you have to write the logic. So you can do a lot more in Redux, but you'll have to potentialy write code that would not be necessary with a specialized library.
You can use them both side-by-side: api cache in react query, rest of your global state in Redux.
That said, the official Redux Toolkit also ships with an api cache abstraction RTK Query since version 1.6 with a similar feature set as React Query, but some different concepts overall - you might also want to check that out.
react-query is designed to deal with data that is stored on a remote server. To access this data, your app needs to use asynchronous requests. This is where you probably want to deal with caching, loading state, network failures, etc.
That is where react-query shines.
Redux on the other ends deals with data on the client-side. For example the content of a text input or the state of a modal. You don't need to deal with network-related issues. But you do need to deal with complex sequences of causes and effects.
That is where redux shines
Redux and react-query are 2 very different things: react-query is used for data synchronization, Redux is a global state manager. react-query is used to keep synch all your apps to the same db, Redux is used to share a part of the app state to all the components that need to read that state.
An example: I have an app to chat with other users. With react-query I keep all the apps synch with all the messages users received, then I store the messages in Redux in order to have messages on chat page and on history chat page.
React Query manages Server State. Its main function is to handle functions between Server and client.
Redux handles client-state. Redux can be used to store asynchronously Data.
So, they have their unique role at different levels and both can be used side by side.
React-Query = server state library(save/cache api response)
Redux = client state library(globally accessible client state
should be stored).
We should distinguish between two kind of states, client state & server (or remote) state:
client state contains:
locally created data that has not yet been persisted to the server.
UI state that handles active routes, selected tabs, spinners, pagination controls, and so on.
server state is everything related to:
data persisted remotely that requires asynchronous APIs for fetching and updating
When it comes to client state, Redux is a grate management tool for managing application’s state.
On the other side, to manage server state, we can use regular state management tools but they are not so great at working with async or server state. So, to resolve this, we use React Query. As described on their documentation, React query is a great tool for:
Caching... (possibly the hardest thing to do in programming)
Deduping multiple requests for the same data into a single request
Updating "out of date" data in the background
Knowing when data is "out of date"
Reflecting updates to data as quickly as possible
Performance optimizations like pagination and lazy loading data
Managing memory and garbage collection of server state
Memoizing query results with structural sharing
You can simply to think:
React Query = axios + cache logic
Redux can store synchronized data and asynchronized data
By the way, I use context manage synchronized state, React Query manage asynchronized state now.

Reactjs with redux, Apollo+graphQL

It opinions based questions .
Need one suggestion.
In Reactjs, is it right approach to use redux for state management and for API call use Apollo + GraphQL?
You have to distinguish between view state (e.g. search field, popup, toggle) and data state (e.g. remote API). Whereas Apollo is mainly used for data state, Redux/MobX/React's Local State are used for view state when used in combination with Apollo Client. If not used with Apollo Client, these solutions can be used for the remote data state too. However, Apollo Client introduced apollo-link-state which can be used for the local view state too.
If your application is purely remote data driven and uses a GraphQL backend, Apollo Client can be sufficient for your application.
If you have a few view states in your application, mix in React's local state management.
If you have several to a lot of view states, use Redux or MobX for your view state or try out apollo-link-state.
That's certainly possible and the natural thing to do. We use this same setup and we found we don't have to use Redux very much anymore.
We used to use Redux to store our API responses (the data) as well, but now Apollo manages that for us.
So our Redux store is now only used for the actual UI state (e.g. routing state, user preferences for certain views, whether something is enabled or not etc).
All data is now retrieved by Apollo and kept in its own internal Redux store, which it uses as a cache. This works great and nicely separates UI state from data state.
I suggest Apollo GraphQl because it has many benefits:
Eliminate Boilerplate
No more action creators, async handling, and request waterfalls. Just ask for the data you need with a GraphQL query, and it shows up.
Validation across the stack
Identify breaking changes in your API before they are deployed, and statically validate data fetching across all of your frontends.
Understand API usage
Learn how your backends are being used with field-by-field granularity. Find and address performance hotspots easily.
Pull complexity out of the client
Put computed fields, data transformations, and security logic into your API so your frontends don't have to reimplement them every time.
Incrementally evolve your API
Add fields to GraphQL as you go and deprecate old fields when you no longer need them. Mock some or all of your API and build the frontend in parallel.
Improve performance
Fetch exactly the data you need, no more and no less. Improve performance with GraphQL-specific caching and optimizations across the stack.
For more Information Read GrapQl Apollo Doc
https://www.apollographql.com/docs/

apollo 2 a replacement for redux?

Is Redux still relavant when using Apollo?
I have recently been diving into Apollo 2, and have seen a notable post stating that they have removed a lot of redux code in favor of Apollo.
https://dev-blog.apollodata.com/reducing-our-redux-code-with-react-apollo-5091b9de9c2a
I know that Apollo 1 used redux under the hood, but that has been deprecated in v2, and several sources have pointed to using apollo-link-state and Apollo Cache as a replacement.
The Apollo Dev tools are super useful but I find myself often wishing to use Redux Dev Tool to be able to see the application global state, use time-travelling and see all that actions called.
It may be that im still getting use to Apollo, but I wanted to know is there still an advantage to using Redux with Apollo?
Update
I have found someone who has build a simple application using Apollo 2, which clearly makes me think think that Redux is completely unnecessary in Apollo.
https://hptechblogs.com/central-state-management-in-apollo-using-apollo-link-state/
State management in a react application is a multi-dimensional issue. It involves coordinating/analyzing states of different components in your screen and managing asynchronous state + data flow (http, persistance, etc.). Apollo started out by only addressing the asynchronous state management. It abstracted away graphql http calls as internals of components. Redux started out on the other side by managing local synchronous state. Today though both solutions are able to provide a local and remote data state management implementation and could be considered interchangable.
The biggest difference between both solutions is the underlying state transition philosophy. Apollo requires less boiler plate by going against the idea of having pure state transitions. On the other hand, Redux follows more of a strict approach to ensuring stat transition occurs in a pure way. I personally like using Redux with GraphQl since Im a big fan of having my state being a result of a series of actions. It keeps things predicatable while still enabling GraphQl to be used by an async handling middleware like redux-saga or things of the sort.
TLDR: Apollo is simpler as it allows the library to do a lot of the async work but comes at the cost of not using Redux's awesome action command pattern.
I have found someone who has build a simple application using Apollo 2, which clearly makes me think think that Redux is completely unnecessary in Apollo.
https://hptechblogs.com/central-state-management-in-apollo-using-apollo-link-state/
Apollo GraphQL Client can also work with any REST endpoint https://www.apollographql.com/docs/link/links/rest.html. So you don't even need to change the backend...

Resources