DEV Community

Cover image for Getting started with React + GraphQL
Tomek Poniatowicz for GraphQL Editor

Posted on • Updated on • Originally published at blog.graphqleditor.com

Getting started with React + GraphQL

How to implement GraphQL in a React app? Let's use React Apollo. This lib will allow you to fetch data from GraphQL server and use it the React framework.

Setup a project

Before you start make sure that you have Node.js installed. To get started we first need to set up a new React project. The easiest way to do so is to use create-react-app, which allows you to create a new React project with zero build configuration.

Setup a react project

Install dependencies

Once you have above done the next step will be to install dependencies. You can do it with a single NPM command which will install the following packages:

Install dependencies

  • apollo-boost: a package with all necessary Apollo Client components
  • react-apollo: a view layer for React
  • graphql & graphql-tag: both required to parse GraphQL queries

Create a client

Now you need to create an instance of Apollo Client. You can do it App.js by adding the following code:

Create Apollo instance

Create GraphlQL Endpoint

To start with, all you really need is the endpoint for your GraphQL server. Let's assume you already have your GraphQL schema created (you can see how to do it quickly here). You can define it in uri or it will be /graphql endpoint on the same host as your app by default.

GraphQL Editor

Connect your React app with Apollo

To connect the Apollo Client to React use the ApolloProvider component exported from react-apollo. The ApolloProvider works similar to React’s context provider:

  • it wraps your React app,
  • places the client on the context,

giving you access to it anywhere in your component tree.

Setting up the connection with Apollo

You made it!

Your first React app with GraphQL is up and running you can start fetching some data with GraphlQL Queries!

Top comments (4)

Collapse
 
daniel15 profile image
Daniel Lo Nigro

Have you compared Apollo to Relay, or to lightweight GraphQL libraries like urql? I'd be curious as to the advantages of Apollo over Relay, and vice versa.

Collapse
 
tomekponiat profile image
Tomek Poniatowicz • Edited

Do not have much experience with Relay, but I think Apollo's biggest advantage (over Relay) is being more elastic and having a much lower entry barrier.

Collapse
 
junibrosas profile image
Juni Brosas

A Github repository for the tutorial is always a nice to have :)

Collapse
 
adeyemiadekore2 profile image
korey πŸ‡³πŸ‡¬

Thanks,
formerly using react-redux, but with apollo and graphQL the automatic data binding to my component is just too sweet.