How to Integrate GraphQL with React.js

Introduction

Using GraphQL with React.js improves how data is fetched and managed in applications. This guide will help you set up a GraphQL server, configure Apollo Client in React, and use GraphQL to query data in your components.

Step 1. Setting Up Your GraphQL Server

  1. Choose a GraphQL Server: Pick a server library like Apollo Server or GraphQL Yoga for your backend.
  2. Define Your Schema: Use SDL (Schema Definition Language) to create types, queries, mutations, and resolvers for your GraphQL schema.
    // Example GraphQL Schema
    type Book {
      id: ID!
      title: String!
      author: String!
    }
    type Query {
      books: [Book!]!
    }
    type Mutation {
      addBook(title: String!, author: String!): Book!
    }
    
  3. Implement Resolvers: Write resolver functions that explain how to fetch or change data for each field in your schema.
    // Example GraphQL Resolvers
    const resolvers = {
      Query: {
        books: () => Book.find(),
      },
      Mutation: {
        addBook: (parent, { title, author }) => {
          const newBook = new Book({ title, author });
          return newBook.save();
        },
      },
    };
    

Step 2. Setting Up Apollo Client in React

  1. Install Apollo Client: Add Apollo Client to your React project using npm or yarn.
    npm install @apollo/client graphql
    
  2. Configure Apollo Client: Create an Apollo Client instance and set the URI to your GraphQL server endpoint.
    // src/apolloClient.js
    import { ApolloClient, InMemoryCache } from '@apollo/client';
    const client = new ApolloClient({
      uri: 'http://localhost:4000/graphql',
      cache: new InMemoryCache(),
    });
    export default client;

Step 3. Writing GraphQL Queries in React Components

  1. Import Apollo Provider: Wrap your React application with ApolloProvider from @apollo/client and pass the client instance created in the previous step as a prop.
    // src/index.js
    import React from 'react';
    import ReactDOM from 'react-dom';
    import App from './App';
    import { ApolloProvider } from '@apollo/client';
    import client from './apolloClient';
    ReactDOM.render(
      <ApolloProvider client={client}>
        <App />
      </ApolloProvider>,
      document.getElementById('root')
    );
    
  2. Write GraphQL Queries: Use GraphQL queries inside your React components to fetch data from your GraphQL server using Apollo Client's useQuery hook.
    // src/BooksList.js
    import React from 'react';
    import { useQuery, gql } from '@apollo/client';
    const GET_BOOKS = gql`
      query GetBooks {
        books {
          id
          title
          author
        }
      }
    `;
    const BooksList = () => {
      const { loading, error, data } = useQuery(GET_BOOKS);
      if (loading) return <p>Loading...</p>;
      if (error) return <p>Error :(</p>;
      return (
        <div>
          {data.books.map(book => (
            <div key={book.id}>
              <h3>{book.title}</h3>
              <p>by {book.author}</p>
            </div>
          ))}
        </div>
      );
    };
    export default BooksList;

Step 4. Running Your Application

To run your application,

  • Start your GraphQL server with the command appropriate for your setup (e.g., npm start for Apollo Server).
  • Launch your React application using npm start and visit http://localhost:3000 (or your configured port) to see your GraphQL-integrated React app in action.

Summary

Integrating GraphQL with React.js enhances data fetching and management efficiency in web apps. By following this guide to set up a GraphQL server, configure Apollo Client, and query data in React components, you can harness GraphQL's flexible querying and React's component-driven structure to develop scalable and responsive applications effectively.