React7 min read

React with GraphQL

Fetch data efficiently with GraphQL and Apollo Client.

Sarah Johnson
December 20, 2025
0.0k0

Use GraphQL for efficient data fetching.

Install Apollo Client

npm install @apollo/client graphql

Setup

import { ApolloClient, InMemoryCache, ApolloProvider } from '@apollo/client';

const client = new ApolloClient({
  uri: 'https://api.example.com/graphql',
  cache: new InMemoryCache()
});

function App() {
  return (
    <ApolloProvider client={client}>
      <Users />
    </ApolloProvider>
  );
}

Query Data

import { useQuery, gql } from '@apollo/client';

const GET_USERS = gql`
  query GetUsers {
    users {
      id
      name
      email
    }
  }
`;

function Users() {
  const { loading, error, data } = useQuery(GET_USERS);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {error.message}</p>;

  return (
    <div>
      {data.users.map(user => (
        <p key={user.id}>{user.name}</p>
      ))}
    </div>
  );
}

Mutation

import { useMutation, gql } from '@apollo/client';

const CREATE_USER = gql`
  mutation CreateUser($name: String!, $email: String!) {
    createUser(name: $name, email: $email) {
      id
      name
    }
  }
`;

function CreateUser() {
  const [createUser] = useMutation(CREATE_USER);

  const handleSubmit = () => {
    createUser({ variables: { name: 'John', email: 'john@example.com' } });
  };

  return <button onClick={handleSubmit}>Create</button>;
}

Remember

  • Fetch only needed data
  • Strong typing
  • Real-time subscriptions
  • Caching built-in

Next: Learn testing advanced!

#React#GraphQL#Apollo#Advanced