Ad

ApolloConsumer VS Import Client

- 1 answer

Why should I use ApolloConsumer instead of importing directly the client in my module ?

From the doc I should do somthing like :

// Module A.js initiate client
const client = new ApolloClient({
  // init cache, links, typeDefs...
});
export default client;
// Module index.jsx
import client from 'A';

ReactDOM.render(
  <ApolloProvider client={client}>
    <App />
  </ApolloProvider>, 
  document.getElementById('root'));
// Any other component not using Query or Mutation
const Other = () => (
  <ApolloConsumer>
  {
    client => {
      // use client
    }
  }
  </ApolloConsumer>);

But why not just import client without ApolloConsumer ?

// Module OtherBis
import client from 'A';

const AltOther () => {
  // do something with client
  return <div></div>;
};
Ad

Answer

Probably for the same reasons why you shouldn't import store directly:

Similarly, while you can reference your store instance by importing it directly, this is not a recommended pattern in Redux. If you create a store instance and export it from a module, it will become a singleton. This means it will be harder to isolate a Redux app as a component of a larger app, if this is ever necessary, or to enable server rendering, because on the server you want to create separate store instances for every request.

Ad
source: stackoverflow.com
Ad