Why

I wanted to use hooks to query a GraphQL API using React Apollo and although it isn't officially supported yet I found a repository that wraps React Apollo in hooks trojanowski/react-apollo-hooks.

I wouldn't recommend this for production use, but I figure the API will be pretty similar once the Apollo team releases official support, so I decided to play around with it in a small personal project.

How?

When I'm learning something new I like to compare the old thing with the new thing and note any differences or similarities. This way of thinking helps me grok new concepts much faster. Sometimes there aren't straight mappings between each thing, but if you can pluck out even a few I think it's a worth while mental exercise.

So that is what we're going to do here. I will show you two almost identical React components side-by-side the first one will show you the new "hooks" way of doing things with react-apollo-hooks as well as <Suspense> and the second one will show the current/old way of doing things with react-apollo.

You can clone this repo to actually try the code out yourself: React Apollo vs React Apollo Hooks

Or if you prefer check it out in CodeSandBox:


The Code Side-By-Side (NewWay vs OldWay)

import React, { Suspense } from 'react';
import ReactDOM from 'react-dom';
import gql from 'graphql-tag';
import ApolloClient from 'apollo-boost';
import { ApolloProvider, Query } from 'react-apollo';
import {
  ApolloProvider as ApolloHooksProvider,
  useQuery,
} from 'react-apollo-hooks';

const client = new ApolloClient({
  uri: 'https://graphql-pokemon.now.sh/graphql',
});

const GET_POKEMONS = gql(`
  query getPokemons {
    pokemons(first: 10) {
      name
    }
  }
`);

// This is the new way using React Hooks and Suspense
function NewWay() {
  const { data, error } = useQuery(GET_POKEMONS);
  if (error) return <div>Error</div>;
  return (
    <ul>
      <h2>NEW WAY</h2>
      {data.pokemons.map((pokemon, index) => (
        <li key={index}>{pokemon.name}</li>
      ))}
    </ul>
  );
}

// This is the old way using render props
class OldWay extends React.Component {
  renderContent = ({ data, loading, error }) => {
    if (loading) return <div>Loading...</div>;
    if (error) return <div>Error</div>;
    return (
      <ul>
        <h2>OLD WAY</h2>
        {data.pokemons.map((pokemon, index) => (
          <li key={index}>{pokemon.name}</li>
        ))}
      </ul>
    );
  };

  render() {
    return <Query query={GET_POKEMONS}>{this.renderContent}</Query>;
  }
}

ReactDOM.render(
  <ApolloProvider client={client}>
    <ApolloHooksProvider client={client}>
      <Suspense fallback={<div>Loading...</div>}>
        <NewWay />
      </Suspense>
    </ApolloHooksProvider>
    <OldWay />
  </ApolloProvider>,
  document.getElementById('root')
);