What are Apollo Client hooks and how do you use them?
Answer
Apollo Client v3 provides React hooks for all GraphQL operations. useQuery: const { data, loading, error, refetch } = useQuery(GET_USERS, { variables: { status: 'active' }, skip: !isLoggedIn, pollInterval: 5000 });. Returns data, loading state, error, and helpers. useMutation: const [createUser, { loading, error }] = useMutation(CREATE_USER, { onCompleted: (data) => navigate('/users/' + data.createUser.id), update(cache, { data }) { /* update cache manually */ } });. Call it with: createUser({ variables: { name: 'Alice' } });. useSubscription: const { data } = useSubscription(MESSAGE_ADDED, { variables: { channelId } });. useLazyQuery: returns a function to trigger the query manually (not on mount). useApolloClient: access the client directly for cache manipulation.
Previous
How do you handle optimistic UI in GraphQL with Apollo?
Next
What is the difference between network-only, cache-first, and cache-and-network fetch policies?
More GraphQL Questions
View all →- Intermediate How do you implement pagination in GraphQL?
- Intermediate What is the Relay specification in GraphQL?
- Intermediate How do you implement authorization in GraphQL resolvers?
- Intermediate What is graphql-shield and how does it work?
- Intermediate How do you implement real-time subscriptions with GraphQL?