Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Redux vs GraphQL
1. July 2018 | Confidential
Redux vs. GraphQL
Lessons learned by Jordon McKoy
2.
3. ● Review of Redux
● Review of GraphQL
● Apollo Client
● Code Example
Lesson Plan
4. Learning
Outcomes
● What is GraphQL and why should I
care about it?
● How can GraphQL help me build
apps?
● Can I replace Redux in my apps
with Apollo Client and GraphQL?
5. 5
Redux Review
Redux is a predictable state container for JavaScript apps.
… It helps you write applications that behave consistently,
run in different environments (client, server, and native),
and are easy to test.
– redux.js.org
“
”
What is Redux?
10. 11
GraphQL Review
GraphQL is a query language for your API, and a server-side
runtime for executing queries by using a type system you
define for your data.
– graphql.org/learn
“
”
What is GraphQL?
20. 22
Why use Apollo?
✓ Provides data binding
✓ Caching + Pagination
✓ Incrementally adoptable
Apollo Client
21. 23
There are only two hard things in Computer Science: cache
invalidation and naming things.
– Phil Karlton
“
”
https://martinfowler.com/bliki/TwoHardThings.html
25. 27
Call REST endpoints inside client queries with apollo-
link-rest
✓ No GraphQL server needed
✓ Data managed by Apollo client
✓ Great for prototyping
Apollo Client
26. 28
Manage state through the local cache with apollo-link-
state
✓ Direct access to the cache
✓ Combine local and remote data
Apollo Client
28. 30
Apollo Client Data Flow
Redux Apollo Client
Dispatch Action Make Query/Mutation
Reducer & store update
Automatic normalization & cache
update
Store Cache
29. 31
✓ Data - external api
✓ Communication - status
✓ Control - forms + UI state
✓ Session - user data + permissions
✓ Location - localization
Now where do I manage state?
30. 32
GenericComponent
Apollo Client
✓ Provide a query for the Query component to fetch
✓ Response is passed to child component using render prop API
✓ Communication state - loading and error props also passed
31. 33
Lesson Plan
✓ Review of Redux
✓ Review of GraphQL
✓ Apollo Client
✓ Code Example
✓ What is GraphQL and why should I care about it?
✓ How can GraphQL help me build apps?
✓ Can I replace Redux in my apps with Apollo Client
and GraphQL?
Learning Outcomes
32. 34
Lesson Plan
✓ Review of Redux
✓ Review of GraphQL
✓ Apollo Client
✓ Code Example
✓ What is GraphQL and why should I care about it?
✓ How can GraphQL help me build apps?
✓ Can I replace Redux in my apps with Apollo Client
and GraphQL?
Learning Outcomes
33. July 2018 | Confidential
@jMcKoy25
jordonmckoy
Q & A
Editor's Notes
About a month and a half ago I wrote a blog post that you can find on the Rangle website taking a brief look at setting up a graphql server with graphql-yoga. For those that don’t know, graphql-yoga is built on top of apollo-server and while I was procrastinating.. Researching for the post I took a look at apollo client and what I read there lead to the idea for this talk.
I’m very excited to talk GraphQL, I find it a very interesting technology due to its implications for not only backend developers or just frontend developers, but all developers no matter what part of the stack they work on.
My title is a misleading however. Redux is a side state management library. GraphQL is a query language for APIs and an alternative for REST backends. They solve two different types of problems and a straight up comparison would be silly. They are like apples and oranges, but it’s a little click-baity so I’m not mad about that.
GraphQL is a server-focused technology and you don’t need much to make calls to a GraphQL server from React and get data. However, it’s recommended to leverage one of the available open source client libraries like Apollo or Relay. These clients make fetching data relatively simple and come with a bunch of great out of the box features that you won’t need to spend time trying to implement yourself.
The Apollo client in particular, has a library that enables us to hook into its cache and use it like a data store. Like we use Redux for its store and state management. So the true comparison, is between Apollo client’s state management potential and Redux.
How many people have used or are using Redux in their React apps?
How many people have used or are using GraphQL in their apps before?
If you had the ability to use it but chose not to, what were the reasons?
“I don’t work on the backend”
“No time to refactor”
Redux is a predictable state container for JavaScript apps.… It helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test
This attributes are important and underline the benefits of Redux
Go over the flow of data in Redux
Knowing what part - Actions keep track of the type of state change and the reducers handle the change.
Imagine a fairly sized app using a simple object to keep state. Any part of your application might be able to modify the state object, it’d be very messy to debug when you don’t know when a change was triggered or even where it came from.
BONUS: passing values from top of the tree to components lower down without needing to use prop drilling. Don’t need Redux for this and don’t need Redux is this is why you use it, you can use the Context API instead but it’s still a great feature of Redux
Predictable - When I dispatch an action, I know what is going to happen and I can see the effect in my reducer. Often taken for granted and sometimes abused (abstractions over top). There is a tradeoff here we’ll discuss in a bit
Single source of truth - A history of changes that enables things like time traveling dev tools and just an easier debugging experience.
Testable - Easy to test, testing reducers and actions is straightforward. Actions are just objects you can make assertions against. Because changes are predictable you can test the effect of your reducers after they’ve been run.
Great ecosystem - Side effect libraries: Redux Thunk, Observable, Sagas. Number of testing libraries. Redux dev tools
Need to be careful not to mutate state
The process - setting up and updating your actions, action types, reducers, selectors, sagas, etc.
Context Heavy
The time tradeoff here is what grants us the predictability
Developed by Facebook, like React
Query language: “a language for the specification of procedures for the retrieval (and sometimes also modification) of information from a database.” like SQL
The impression it’s server only, it IS definitely a server first technology but there are ways to use GraphQL as more than that as we’ll see shortly
The query language starts with the schema.
You build a schema by defining custom types - models of your data
and defining resolvers that tell GraphQL how to produce results when these types are queried.
Participation: Missing something, can someone tell me or guess what is missing from these type definitions? (ID field)
** Restaurant meal type - name of meal, price, origin
Restaurant analogy
Restaurant is your app logic ( server )
Client is a customer
Schema is the menu
Server is the chef
Resolver is a recipe
Making a query = ordering food
Basic scalar types: Int, Float, Boolean, String, ID
Custom scalar types require you to define how it is serialized, deserialized, and validated
Familiar JSON shape
Meal query - who ordered it, name of meal, price : Jerk chicken, Jordon ordered it, 12.99
MUTATION
Meal query - who ordered it, name of meal, price : Jerk chicken, Jordon ordered it, 12.99
Calls from client -> GraphQL server -> makes calls to data sources -> data gets sent back down
GraphQL server connects multiple data sources and endpoints into one endpoint
This encourages teams to move logic around the retrieval and transformation of data from the client to the server. A drawback is the increased load to backend teams. However, frontend teams can now focus on building better user experiences instead of data transformation code. Something like sorting paginated data makes sense to do it on the server anyway, why not have that built once in your server instead of reimplementing code to handle this across all your clients.
The client should just be a customer of your app’s restaurant, never in the kitchen with the chef.
This helps to build consistency in your app across different environments, values that we saw earlier, were to key to Redux and are key to building GraphQL powered apps
Particularly with REST
Multiple client round trips - There is a single endpoint the client makes calls to. This means the client can drastically reduce the amount of traffic from the client to server or third party APIs. Ability to batch queries. This is a big win for mobile clients, reducing network calls not only reduces impact on data
Bloated REST responses - Making a REST call at times feels asking someone a simple question and getting their life story as an answer. Fitting with the restaurant analogy, not being able to request modifications to your meal. With GraphQL queries you specify the exact data you want and get no more, no less. Another win for mobile clients where there is more emphasis placed on smaller payloads.
Declarative - Consistent with a query language like SQL and even React, GraphQL queries are declarative. We simply ask for data and GraphQL figures out how best to supply it to us
Self documenting - The schema gives you an overview of the surface area your API covers. Developers can study it and get a picture of how data is related and how they can interact with it. Tools like Graphiql (Repl like environment with introspection that allows you to see every query or mutation possible) for your team or the public to experiment with, great for open source projects
Nested queries - With REST it’s common to make calls to multiple endpoints to retrieve enough data to build the shape your component needs. With GraphQL you can get all the data your component needs in one call, even if the data lives in different data sources. Eg. If order type data lived in a database and meal type data lived in a third-party api
Works all across the stack - Client libraries with native support and multiple server implementations (Ruby, means a consistent way to manage data in all parts of your application stack
GraphQL best practices encourage avoiding versioning of your endpoint instead, favouring the continuous evolution of your schema. With REST there can be little control over the data returned (from a client perspective), any change to an endpoint could be considered a potential breaking change. With GraphQL you’re free to add new fields and new type to add functionality. This can be useful for open source projects that find maintaining multiple versions of endpoints a challenge
GraphQL is not a silver bullet, it’s a tool, like Redux, and can be overkill for a project when it’s not truly needed. Developer discretion is always required.
Schema and resolver definition - Not only does your schema need to be in defined (what is your data), you need to define resolvers to tell GraphQL how to resolve your queries. (how to find your data). This is another trade off and how GraphQL works to maintain type integrity
Can be slower than multiple REST calls - I feel one of the misconceptions surrounding GraphQL (maybe not so much these days) is that it is faster than REST. “I only need to make a single call to a GraphQL endpoint to fetch the same data that used to take 3 calls to a REST endpoint”. Those REST calls didn’t evaporate, they still exist, they’ve just been moved from the client to the server. However, if the calls were against your own database and not from a third party API and you used something like Prisma in front of your database, I can see that definitely being faster than a REST approach.
Foundational libraries in their ecosystem of GraphQL tools
Client: Binds data to React
Engine: Gateway that adds some features like another cache layer, performance and error tracking
Server: Run-time, facilitates the connection of multiple data sources
Open source
Works with any GraphQL server
When you install Apollo Client, you get caching + pagination out the box. You get options for refetching queries, retrying requests, and polling out of the box as well.
Dev tools
Let’s see where the cache fits as data flows through the Apollo client
Query is like dispatching action
Automatic normalization and caching
Subscription of changes
The automatic caching in Apollo client is great.
All network responses are normalized, response data is split into individual objects and assigned a unique identifier and typename property, storing them in a flattened structure.
Will pull data already loaded in the cache instead of making another network request if possible.
We’ve looked at how Apollo stores data in the cache, how can we possibly use this cache to manage our own state? The answer is with Apollo Links!
Apollo Link is a pluggable network interface layer, a system of modular components for GraphQL networking. My mental model is to think of these links like middleware for the Apollo client
Error
Context
Batching
Websockets
The two I’d like to highlight are apollo-link-state and apollo-link-rest
It’s easy to think of it as a middleware that hooks into the cache. This link is the key to enabling Apollo client as a tool for state management.
It exposes functions that allow you to read and write directly to the cache.
The link-state and link-rest add more data sources
We can query local cache and rest api the same way as we would a graphql server. Again, consistency in how we interact data
Pretty powerful but 2 stores creates a potential problem. They CAN live together, requires a delegation of responsibilities. Keeping both removes a single source of truth
1 stores makes it easier to debug, persist state
Once more, Redux and GraphQL are two very different things.
I’m really trying to hammer home how we’re able to use the Apollo Client cache for many of the same things we use Redux for.
Comparison when using Redux for data fetching
James K Nelson
Data - from external apis
Communication - api flight status
Control - forms, component/view specific state, filters
Session - user data, permissions
Location - localization info, usually kept in URL
Before looking at the code examples, I want to introduce and talk about a couple of the components made available through the client.
New in the latest version of Apollo Client is the Query component, and the preferred way to declaratively fetch data. You use it by passing a graphql query to it and apollo will fetch your data for you. It uses a render prop API so it will pass the result to its child. This child being your wrapped component. Along with the result, the Query component also passes a loading and error prop that can be used to render different states of your component.
The mutation component triggers mutations or changes to your data. It is similar to the query component in that you pass it a graphql mutation but the along side the data, loading, and error props, a function is passed to your child component, allowing you to trigger the mutation based on some user interaction.
Both come with great additional options and features, for example, Query component has built it options to manage refetching data and retrying requests, as well as polling out of the box
- - - - - - -
Single purpose components
The query lives with the component - no file switching
Personally, I’ve found using the render prop API encourages building components that a single purpose, otherwise the nesting can get out of hand quickly.
Pros & Cons. Testing. Number of components to make. It was unfamiliar
Apollo exposes a compose function, similar to the compose function from Redux or a library like recompose
Why should I care? - advantages over REST (nested queries and payload size)
How can it help me? - Encourages moving lots of logic to backend, smaller client responsibilities. Single purpose components.
Why should I care? - advantages over REST (nested queries and payload size)
How can it help me? - Encourages moving lots of logic to backend, smaller client responsibilities. Single purpose components.
Can I replace Redux? - For data layer operations, yes you can in the vast majority of cases. But for the rest of state, should you?
Keep in mind your tech stack,
team competencies,
timelines,
cost considerations (server cost)
etc.