Published on

February 6, 2023

Building Scalable React Applications with GraphQL

Introduction

In today's modern application development, the need for a quick and easy solution to build complex and dynamic applications is growing. GraphQL is quickly becoming the preferred choice for many developers who want to create powerful, data-driven experiences. In this article, we will explore how GraphQL can be used to create scalable React applications and how it can be optimized for them.

What is GraphQL?

GraphQL is an open-source query language for APIs. It provides a simple and powerful way to query and manipulate data from any source. Unlike a typical REST API, GraphQL allows developers to define the shape of the data they need, and the server will provide the data in the exact format requested. This helps reduce the amount of data sent, as the server only sends the data that is requested.

  • GraphQL simplifies the process of data retrieval, as developers don’t need to make multiple requests to get the data they need. With GraphQL, developers can retrieve all the data they need with a single request, saving them time and effort.
  • GraphQL also makes it easier to query and manipulate data, as the GraphQL query language is easy to learn and understand. With GraphQL, developers can quickly and easily write queries to get the data they need, and they can easily modify existing queries to get different results.
  • GraphQL provides a way to easily add new features and data to an application without having to make significant changes to the existing codebase. This makes it easier to build new features on top of existing data models, allowing developers to quickly and easily add new data and features to their applications. Additionally, GraphQL makes it easier to integrate different data sources, allowing developers to bring together data from multiple sources into a single API.

Creating a React project

Vite is a modern web development build tool that is optimized for performance and developer experience. It is lightweight and provides an instant development server with zero configuration. With Vite, developers can create high-performance React applications quickly and easily.

To get started, we can create a React application with Vite by running the following command in the terminal:

npm create vite@latest my-react-app -- --template react

This will create a new React application in the my-react-app directory. From there, we can install the necessary GraphQL packages and configure them for our application.

Setting up a GraphQL Server

To setup the Apollo server, you will need to install a few packages. First, you will need to install the Apollo server package along with the GraphQL library:

npm install @apollo/server graphql

Create a new file apollo.js inside the src directory. This file is used to set up the Apollo Server, which allows us to connect our React application to a GraphQL API. Add the following code to apollo.js to get started:

src/apollo.js
import { ApolloServer } from "@apollo/server";
import { startStandaloneServer } from "@apollo/server/standalone";

const typeDefs = `#graphql
  type Book {
    title: String
    author: String
  }

  type Query {
    books: [Book]
  }
`;

A data set is a collection of data that can be used to build an application. In the context of Apollo Server, the data set is the collection of data that will be used to create the API and queryable objects that the React application can use to interact with. Next, you need to define the data set in the same file:

src/apollo.js
import { ApolloServer } from "@apollo/server";
import { startStandaloneServer } from "@apollo/server/standalone";

const typeDefs = `#graphql
  type Book {
    title: String
    author: String
  }

  type Query {
    books: [Book]
  }
`;

const books = [
  {
    title: "The Awakening",
    author: "Kate Chopin",
  },
  {
    title: "City of Glass",
    author: "Paul Auster",
  },
];

Resolvers are functions that are used to populate the data for a GraphQL query. In Apollo, they are responsible for fetching the data from the underlying data sources and returning the requested information in the proper format. You need to define the resolvers in the same file:

src/apollo.js
import { ApolloServer } from "@apollo/server";
import { startStandaloneServer } from "@apollo/server/standalone";

const typeDefs = `#graphql
  type Book {
    title: String
    author: String
  }

  type Query {
    books: [Book]
  }
`;

const books = [
  {
    title: "The Awakening",
    author: "Kate Chopin",
  },
  {
    title: "City of Glass",
    author: "Paul Auster",
  },
];

const resolvers = {
  Query: {
    books: () => books,
  },
};

Creating an instance of ApolloServer is necessary in order to set up a GraphQL server that can handle requests and responses sent by React applications. This is essential for building scalable React applications as it allows for efficient data fetching and management. You need to create an instance of ApolloServer in the same file:

src/apollo.js
import { ApolloServer } from "@apollo/server";
import { startStandaloneServer } from "@apollo/server/standalone";

const typeDefs = `#graphql
  type Book {
    title: String
    author: String
  }

  type Query {
    books: [Book]
  }
`;

const books = [
  {
    title: "The Awakening",
    author: "Kate Chopin",
  },
  {
    title: "City of Glass",
    author: "Paul Auster",
  },
];

const resolvers = {
  Query: {
    books: () => books,
  },
};

const server = new ApolloServer({
  typeDefs,
  resolvers,
});

const { url } = await startStandaloneServer(server, {
  listen: { port: 4000 },
});

console.log(`🚀  Server ready at: ${url}`);

Next, update your package.json file to include the client and server scripts:

package.json
{
  "name": "my-react-app",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "client": "vite",
    "server": "node src/apollo.js",
    "build": "vite build",
    "preview": "vite preview"
  },
  "dependencies": {
    "@apollo/client": "^3.7.7",
    "@apollo/server": "^4.3.2",
    "graphql": "^16.6.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
  },
  "devDependencies": {
    "@types/react": "^18.0.27",
    "@types/react-dom": "^18.0.10",
    "@vitejs/plugin-react": "^3.1.0",
    "vite": "^4.1.0"
  }
}

If you run npm run server, the GraphQL server will start running at http://localhost:4000. Next, you can replace the existing query with the following code to get a response from the GraphQL server:

query GetBooks {
  books {
    title
    author
  }
}

If you click on the GetBooks button, you should be able to view the following response from the GraphQL server:

{
  "data": {
    "books": [
      {
        "title": "The Awakening",
        "author": "Kate Chopin"
      },
      {
        "title": "City of Glass",
        "author": "Paul Auster"
      }
    ]
  }
}

Connecting React to GraphQL

With the GraphQL server configured, we can now move onto integrating GraphQL into our React application. Apollo Client provides a simple way to connect a React application to a GraphQL server. It provides an easy-to-use API that allows developers to quickly and easily fetch data from the GraphQL server.

To get started, install the necessary Apollo packages:

npm install @apollo/client

Next, create an instance of ApolloClient and configure it to connect to the GraphQL server. Inside the src/main.jsx file, include the following code:

src/main.jsx
import { ApolloProvider, ApolloClient, InMemoryCache } from "@apollo/client";
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import "./index.css";

const client = new ApolloClient({
  uri: "http://localhost:4000/",
  cache: new InMemoryCache(),
});

ReactDOM.createRoot(document.getElementById("root")).render(
  <React.StrictMode>
    <ApolloProvider client={client}>
      <App />
    </ApolloProvider>
  </React.StrictMode>
);

The ApolloProvider component provides the ApolloClient instance to all of the components in the React application, allowing them to access the GraphQL server.

To get data from the GraphQL server, developers can use the useQuery hook in their components:

src/App.jsx
import { gql, useQuery } from "@apollo/client";
import "./App.css";

function App() {
  const { loading, data } = useQuery(gql`
    query GetBooks {
      books {
        title
        author
      }
    }
  `);

  if (loading) {
    return "Loading...";
  }

  if (data) {
    return data.books.map((book) => (
      <div key={book.title}>
        <h2>{book.title}</h2>
        <p>{book.author}</p>
      </div>
    ));
  }
}

export default App;

The useQuery hook takes a GraphQL query as an argument and returns an object containing the data and loading state. With the useQuery hook, developers can easily fetch data from the GraphQL server in their React components.

If you visit http://localhost:5173, you should able to view the titles of the books and their author names.

Advanced Topics

Caching

Caching is an important topic when it comes to GraphQL and helps to reduce the number of requests that need to be made to the server, as well as improve the performance of the application. There are a number of strategies that can be used to implement caching in a GraphQL application, such as using Apollo Client's InMemoryCache, HTTP caching, or Redis caching. It is important to understand how caching works in order to properly utilize it.

Security

Security is another important topic when it comes to GraphQL. It is important to ensure that the data being sent to and from the server is secure and that it is not being accessed by unauthorized users. There are a number of strategies that can be used to ensure that the data is secure, such as using authentication and authorization techniques, as well as encrypting data.

Conclusion

In conclusion, GraphQL is a powerful tool for building modern applications. It allows developers to query and manipulate data quickly and easily, making it a great choice for creating complex and scalable React applications. Furthermore, GraphQL provides developers with powerful tools such as caching and security, which can be used to further improve the performance and security of the application. With its powerful features, GraphQL is an invaluable tool for creating powerful and reliable applications.

This post was updated on

February 6, 2023.