Menu

Apollo Client for Beginners: GraphQL Data in React Made Simple
📰

Apollo Client for Beginners: GraphQL Data in React Made Simple

DEV Community: graphql·Arhan Khan·12 days ago
#Vtt3oiYH
#devtographql#devto#dev#apollo#client
Long article (355 words) — no AI summary yet.
Reading 0:00
15s threshold

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 .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.