Oh Hello Apollo Client ๐, Goodbye Redux! ๐
I know I got excited with the title there but it is kinda true ๐ . In this blog post, I will cover why your switch to GQL and Apollo Client 3 should make you walk away from Redux. I will also talk about my journey from Redux -> Apollo Client.
I have had my share of doubts so in the past couple of projects, I was really skeptical of using Apollo Client as a state management solution. I love โค Apollo and specifically the changes made in Apollo client 3 that changed my mind completely ๐ป
Why I like Redux and what it is good at ๐
- Global state management solution where you have a good visual of your entire state
- You use actions to trigger state updates and asynchronous requests (love ๐ my boo: Redux saga ๐)
- The entire ecosystem is amazing, you get Redux time travel too for debugging! โฒ
- You can use libraries like Redux selectors (another awesome library ๐) to select data from the state and transform
which brings me to my next pointโฆ ๐
What is considered a good state management solution? โ
- My data is normalized (no dupes please ๐)
- Specific actions i.e. user logging in / routing should be able to trigger asynchronous requests ๐ฏ
- We want to transform the data so that our component is not huge and we can write tests!! ๐ต
- Lastly, visualize the store i.e. we can view our global state and debug easily ๐
and Iโm sure there are more but the above were the top ones in my list! ๐ฅ
After I started using GQL โจ
- I didnโt use Redux in the GQL project because we were using React Hooks and React Context and it felt repetitive because you can use
useReducer and useContext
where you can dispatch actions and update state - Apollo Client exposes custom hooks โ๏ธ like
useQuery
,useMutation
which automatically exposedloading
,success
anderror
states so I didnโt need to trigger 3 different actions in my redux store i.e.CART_REQUEST
,CART_SUCCESS and CART_ERROR
. For example, here is a comparison โก๏ธ
A lot of boilerplate code has reduced ๐ You get the loading
, success
, and error
states right from the useQuery
and useMutation
hook.
So what was missing? ๐
Going back to the definition of a good state management library ๐
- I really loved
useQuery
anduseMutation
custom hooks although I wasnโt fully convinced to switch for state management completely as I really liked using Redux selectors that select data & we have the ability to transform it ๐ฅ - In the meanwhile, I was using React Context instead of Redux
- I also didnโt want to read the Apollo cache all the time
- At the time, there was no way to store values outside the cache
- I also wanted actions to trigger asynchronous requests like Redux sagaโs do ๐ถโโ
- On top of this, I found Apollo client cache really hard to read ๐ซ
But with Apollo Client 3, they introduced Reactive Variables and local only fields that changed everything ๐
Apollo Client 3 gives us 2 really cool things ๐
- Local only fields
- Reactive Variables
They are fields that resolve on the client side itself by reading data from the cache if you want thus replacing the transformers in Redux. Letโs take a look how that would work.
My data is normalized (no dupes please ๐)
Apollo Client takes care of the heavy lifting for you ๐ช. You donโt need to constantly dispatch actions to change state. With redux, we were really used to that and the benefit there is you have full control although do we really need full control? ๐ถ
You are already using GQL โค๏ธ so everything is a graph ๐ and is stored in the graph i.e. you already have all your data in your cache then why add Redux on top to duplicate it? ๐คทโโ You are going to add more overhead ๐
Apollo Client automatically caches your data and normalizes new data in query responses and after mutation. Similar to what you would do in Redux where you would need to make sure that your data is normalized. If you are onboarding a new developer, itโs hard because they also need to consider and learn how to do this on an architecture level which adds more overhead.
Apollo client stores data using references so it can be smart by looking it up easily using that reference as a key. Here is an awesome blog post ๐ written by Khalil Stemmler on Demystifying Apollo Cache which you should read before switching to AC3 for state management. ๐ฏ
Data transformations ๐
We want data transformations in an application so there is a clear separation of side-effect to transform layer. This way we can make sure that our component file is not huge and we can write tests for those transformers
We will use local only fields mainly for transforming data.
1. Local only fields ๐ผ
Local only fields is a way we can define client side fields on the GQL type that doesnโt need to come from the server. You can resolve them locally on your frontend.
Letโs say we have the following query for getting the userโs cart โก
Here is how your cart query data object from the above query looks like ๐
Letโs say we have this user story, ๐
As a user, I want to see if an item is out of stock or low stock based on the items in my cart.๐ฉ๐ฝโ๐ป
Here is how your React component might look like for it without using the Apollo client side variable: ๐ โก๏ธ
Typically in Redux, we would extract the logic of the function getTextForLowOrOutOfStock
outside using a redux selector. ๐
With AC3, you can achieve the above by reading the cache and adding the string for โout of stockโ and โlow stockโ accordingly within your client itself.
OK But, how can we use local only fields? ๐ค
We can create local only fields on the Cart type with the @client
directive. ๐ For example, โก๏ธ here stockText
is the client side field.
With the @client
directive, Apollo client will look into the cache to resolve the field. It wonโt make a call over the network for that field because of the directive. Now stockText
can be accessed anytime we declare a Cart
type because it is a field on the Cart
type.
Now we can directly access stockText
in our React component by doing the following โก๏ธ
2. Reactive Variables ๐ธ
We can also create custom client side values stored outside the cache known as Reactive Variables. Sometimes we just want to create a field outside of the type structure which can still be accessed through the Apollo client globally. For that, Apollo client gives us Reactive variables.
Modifying a reactive variable triggers an update of every active query that depends on that variable, as well an update of the react state associated with any variable values returned from the
useReactiveVar
React hook.
Reactive variables donโt update the cache but store the state information that we want to access at any point in our application. In Redux, we usually dispatch an action to store such a value in the store.
Letโs say we have this user story, ๐
As a user, I want to view the number of items in my cart that are on sale. ๐ฏ ๐ฉ๐ฝโ๐ป
For this you would have to read all the items in cart, check items that are on sale and count them. With Apollo client, you can achieve this by ๐ โก๏ธ
You can do way more than this. You can also access existing fields (i.e. readNumberOfOOSItems
) through other fields as well. ๐
You can access the above readNumberOfOOSItems
via a query as well which gives you loading, data and error
states:
But wait, what is the difference between local only fields and reactive variables? ๐ค
In a local only field, you create a new field on the type itself i.e. from our example, we created stockText
on the Cart type
i.e. you canโt access stockText
anywhere else.
But for reactive variables, you can access it anywhere you like and it isnโt restricted to a specific type. Unlike the Apollo Client cache, reactive variables donโt enforce data normalization, meaning you can store data in any format you want. ๐คฏ
Specific actions should trigger asynchronous requests โฉ
Once we do retrieve data or if the user wants to route based on certain information from the server, we might want to trigger asynchronous requests or rather specific actions that the user should take.
Letโs say we have this user story, ๐
As a user, I want to be taken to the sign in page if Iโm not logged in else I want to see the app page
Here we want to track if the user is logged in or not and accordingly route the user. We can achieve this by creating a reactive variable for it.
Reactive variables are variables stored in the client and outside the cache but the components can also access their values directly. In the example below, isUserLoggedIn
is a reactive variable that has been created using makeVar
function. It invokes the function to check if there is a token in the browser Cookies๐ช. (In the real world, we will obviously check for token expiry as well ๐).
Anything under fields is a field policy. A field policy is basically a contract between client and the function which dictates how that field is going to be resolved. We have a field policy to read the number of out of stock items and check if the user is logged in or not.
Next, in order to access this value within the component, we can do the following โก๏ธ
The above will re-render whenever the value changes for isUserLoggedInVar
If you want to trigger an API request once the user has logged in, you can achieve this by listening to isUserLoggedIn
in a useEffect
. ๐
Therefore, we can trigger async requests based on whatโs in the state.
But wait, can I update the value of the Reactive variable? ๐ค
Yes you can! We can update the value of the reactive variable anywhere in our application, for example if we wanted to update the value of isUserLoggedInVar
to false
or anything else, we can! We just need to invoke the function isUserLoggedInVar
directly!
Visualize store / cache ๐ฎ
Lastly, visualize the store i.e. we can view our global state and debug easily
Just like Redux developer tools, Apollo client also have their developer tools, here is a link. ๐ Initially, I had some difficulty visualizing the cache as the Apollo developer tools are not as mature as Redux developer tools.
But after understanding how Apollo client stores data internally and how it optimizes it, things got a lot easier. I am able to visualize the cache. ๐
In the Queries and Mutation tab, you will see a list of Queries and Mutations executed in your application (just like Redux does). In the cache tab, you will see the entire cache i.e. your Root query along with the cache references that got updated.
You can use GraphiQL to query anything (including Reactive variables) just like you would in the GQL playground. But if you want to query Reactive variables, make sure to check the checkbox โLoad from cacheโ.
While I missed the time travel feature provided by Redux Dev Tools, once I learned what the cache looked like and how much it took care of, things became simpler to reason about. I would say lack of time travel is definitely a pain point of Apollo client dev tools overall ๐ค
Lastly, keep an open mind โ๏ธ
- The difference between Redux and Apollo Client is that you either take control and do everything on your own (like Redux) or let a mature library like Apollo Client handle that for you ๐
- Donโt get me wrong, I do love control ๐. but Apollo client is taking care of the bulk of the work for you so you can focus on the core of your application
- I kept comparing Apollo client to Redux 1:1 and although it was great to help me understand how my app would scale, this was also a reason I was holding back because now I have to unlearn what I have learned and trust that Apollo client will take care of it for you. ๐
- When you are using Apollo client, it does feel redundant to use Redux on top of it as you are now keeping 2 copies of the same data i.e. Apollo client cache and Redux global store. ๐
- The more you learn about the cache, the more you start to love it! โค๏ธ
Thank you for making it so far, hope you found this post useful ๐ฏ and it helps you draw comparisons between Redux and Apollo Client. ๐
If you found this helpful, I write a weekly newsletter on content related to front-end development, leadership, career development, my journey into content creation, and lots more behind the scenes that I donโt share anywhere else. If you would like to know more or would like to subscribe, visit the link below.: https://kulkarniankita.com.