GraphQL gives you exactly the data you ask for, but someone still has to send the query, handle loading and errors, cache the result, and update the UI. Apollo Client is the most popular GraphQL client for React, and it handles all of that with a few hooks.
First you set up the client once, pointing it at your GraphQL server:
import { ApolloClient , InMemoryCache , ApolloProvider } from '@apollo/client' ;
const client = new ApolloClient ( { uri : 'https://api.example.com/graphql' , cache : new InMemoryCache ( ) , } ) ;
Enter fullscreen mode
Exit fullscreen mode
Then fetching data in a component is one hook:
import { gql , useQuery } from '@apollo/client' ;
const GET_USERS = gql ` query GetUsers { users { id name email } } ` ;
function UserList ( ) { const { loading , error , data } = useQuery ( GET_USERS ) ;
if ( loading ) return < p > Loading . . . </ p > ; if ( error ) return < p > Error : { error . message } </ p > ;
return data . users . map ( ( user ) => < p key = { user . id } > { user .…