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...
Related
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
I'm new in Next.js and GraphQL world. So far i've been using react with reduxjs and axios for API calls. I would learn more advanced stuff so here is my question. If i'm using apollo graphql what options do i have for local state management? It can be handled by apollo itself or i should use external tool like redux store?
Apollo at its heart is a GraphQL implementation that helps people manage their data. They also make and maintain a GraphQL client (Apollo Client) which we can use with React frameworks like Next.js.
The Apollo Client is a state management client that allows you to manage both local and remote data with GraphQL and you can use it to fetch, cache, and modify application data.
In this article, we’ll discuss why we should use the Apollo Client with Next.js and how we can use the Apollo Client with Next.js to render pages via the three rendering methods Next.js supports; static site generation (SSG), server-side rendering (SSR), and client-side rendering (CSR).
If you want to use your Redux and Apollo state in a component, you need to use both graphql from react-apollo and connect from react-redux. This will let you better track the different events that happen in your app, and how your client and server side data changes interleave.
Why use Apollo Client with Next.js
First, let’s look at why we should use the Apollo Client with Next.js. There are three key reasons to use the Apollo Client:
Out-of-the-box support for caching
Built-in loading and error states
Declarative approach to data fetching
Out-of-the-box support for caching
In Apollo’s own words, “Caching a graph is no easy task, but we’ve spent two years focused on solving it.”
Apollo has invested serious amounts of time in making their caching process the most efficient and effective they can. So, why try and reinvent the wheel? If you’re fetching data in your application and working with GraphQL, then the Apollo Client is a great way of handling your data.
Another benefit is that there is minimal setup required for developers using the client. Apollo even labels it as “zero-config.” We will see this in our application example further in the post, but to set up caching in an application, all we need to do is add the code below to our application:
import { ApolloClient, InMemoryCache } from '#apollo/client';
const client = new ApolloClient({
cache: new InMemoryCache()
})
Built-in loading and error states
The Apollo Client has a custom React Hook built into it called block useQuery, which we will use in our example application, and gives us built-in loading and error states for us to use.
While this doesn’t sound impressive, what it means for developers is that we don’t need to spend time implementing this logic ourselves, we can just take the booleans the Hook returns and change our application rendering as required.
Thanks to these built-in states, using the Apollo Client means we can spend less time worrying about implementing data fetching logic and focus on building our application.
Declarative approach to data fetching
Another benefit of the way the Apollo Client implements the useQuery Hook is that data fetching with the Apollo Client is declarative rather than imperative.
What this means for us is we only need to tell Apollo what data we want and it gets it for us. We don’t need to write the logic and give it a list of step-by-step instructions on how to do it or handle it.
Once again, this is another great example of how the Apollo Client helps speed up development and make us more efficient developers when working with GraphQL.
You can learn more in this page right here if why use nextjs with apollo: This link
By default, Apollo Client creates its own internal Redux store to manage queries and their results. If you are already using Redux for the rest of your app, you can have the client integrate with your existing store instead.
In simple words, When you're using Apollo, you shouldn't be putting that data into Redux. You can still use Redux for other things, but apollo's duty is to store that data and make it accessible to your components. Taking it out and putting it into Redux means doing double the work for no added gain, and there's a strong risk you'll introduce a lot of asynchrony between the two levels as a result.
Referenced from here:
enter link description here
And learn more if u want to integrate redux and apollo from here: enter link description here
Learn more if it is necessary to use redux with apollo right here as well: enter link description here
So most of my projects are simple enough that Redux has been total overkill (even though it's worked really well always) - I am going to use Context API on a new project (it will easily do the job, and it's way easier to explain to other devs and get them going on) - Redux has Thunk to handle async actions. I think I understand things well enough to reason that async actions will not be a problem for Context API - Redux Thunk doesn't actually add async functionality to Redux - it simply makes the syntax more palatable. So my reasoning says that Context API will be able to handle any async actions as long as I write code to correctly deal with them. Is this right, or do I need to stick to Redux with Thunk if I want to handle async actions effectively?
I had similar question myself and came across this article that talks about a major difference between Redux and the Context API:
From https://www.academind.com/learn/react/redux-vs-context-api/
The Context API (currently) is not built for high-frequency updates (quote of Sebastian Markbage, React Team), it’s not optimized for that. The react-redux people ran into this problem when they tried to switch to React Context internally in their package.
My personal summary is that new context is ready to be used for low
frequency unlikely updates (like locale/theme). It’s also good to use
it in the same way as old context was used. I.e. for static values and
then propagate updates through subscriptions. It’s not ready to be
used as a replacement for all Flux-like state propagation. ---
Sebastian Markbage
So for the moment, it seems like you might want to look into using React Context for low-frequency updates (e.g. theme changes, user authentication) but not use it for the general state management of your application.
Hope this helps.
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/
I've been using Redux for months now and I realized that using Redux actually slows down my dev speed a lot (sorry that the title is provocative). I separated the backend and frontend completely into two repos. I use Rails on the backend and Redux on the frontend.
It feels very nice to be following the modern ES6 trend with React, Redux, and Babel. But these two things bother me:
You have to write a LOT of code just to get CRUD right. Getting the loading state right, making sure that the frontend and backend data are always in sync, etc. is more hassle than you might imagine.
You have to worry about SSR, which is not all that simple.
So I went ahead and re-wrote my app in Rails and React without using Redux. Basically, I just used React to draw presentational components, and Rails controllers replaced Redux's smart containers. Then, I could implement the same functionality twice as fast.
When should I actually use Redux? Am I doing something wrong?
The major benefit of Redux is the single source of truth for your application's data, paired with powerful features like middlewares (super useful for tracking things like telemetry.)
From a usage POV it's not much more complicated than any other Flux implementation, but you gain the benefit of access to all state all the time instead of cobbling together pubsub subscriptions to a bunch of stores.
I've been using it for about 8 months now and have few complaints.
When I started using React Native I didn't use redux, I was spending a lot of time sending data from one component to another, from one module to another and the code was getting ugly as my application started growing, until I integrated redux.
Redux allows you to share data across all your application with easy, allowing you to change the global state with a simple action call from your components.
I use Rails as well for the backend but only to save and get data. I have a JSON API that I use from the mobile app (React Native) and from a web app that I have in AngularJS.