Apollo Client: Cache Normalization and the Death of Redux Boilerplate
It's 2016, and many of us are drowning in Redux. Every API call requires an action creator, a reducer, a constant, and a selector. If you have two components showing the same "User" data and one updates, you have to manually ensure the other one stays in sync.
Apollo Client handles all of this for you using the InMemoryCache.
How Normalization Works
Apollo is smart. It looks at the id and __typename of every object returned by your GraphQL server. It then flattens these objects into a global, normalized cache.
If you fetch a list of "Posts" and then later fetch a single "Post" with the same ID, Apollo knows they are the same entity. Update one, and every component using that ID updates automatically.
The graphql HOC
In 2016, we're using Higher-Order Components (HOCs) to connect our components to data.
import { graphql } from 'react-apollo';
import gql from 'tag-gql';
const PostList = ({ data: { loading, posts } }) => {
if (loading) return <div>Loading...</div>;
return (
<ul>
{posts.map(post => <li key={post.id}>{post.title}</li>)}
</ul>
);
};
export default graphql(gql`
query GetPosts {
posts {
id
title
__typename
}
}
`)(PostList);
Why It's a Revolution
- Declarative Data Fetching: Just describe what you need.
- Automatic Sync: No more manual reducer logic for data updates.
- Optimistic UI: Apollo makes it easy to update the UI before the server even responds.
In 2016, GraphQL and Apollo are making Redux feel like "low-level plumbing" that we finally get to stop writing.
Aunimeda develops websites and web applications for businesses - corporate sites, e-commerce, portals, and custom platforms.
Contact us to discuss your web project. See also: Web Development, E-commerce Development