If you’re looking to start a new Apollo project, we recommend installing the following package after you’ve set up your Apollo Client instance:
npm install @apollo/react-hooks
This package exports the ApolloProvider component to connect the client to your React app, just like the old API.
If you already have an Apollo project, you have a couple options depending on how you want to transition to hooks. Read the migration guide to learn more about upgrading.
Why Hooks are the future ⚓️
Apollo Client still supports its higher-order component and render prop APIs, and it will support them for a while. Going forward, we think hooks are the best way to fetch data with Apollo Client. While you don’t need to migrate all of your old components right away, you should adopt hooks for new components. Here’s why:
Less data management code
Hooks reduce boilerplate and unnecessary data management code, which leads to smaller components that are easier to reason about.
You no longer have to understand how to compose higher-order components or trace complicated render prop logic. Fetching data is as straightforward as calling a single useQuery function:
When you’re working with multiple mutations in a single component, higher-order components and render props can produce code that is difficult to understand. With the render prop API, the nesting of multiple Mutation components creates a false sense of hierarchy.
The new useMutation hook avoids this issue entirely since we’re simply calling a function. The example below demonstrates how multiple mutations and a query can interact with each other, all from within the same component:
You can see multiple mutations in action here. This example app also includes a similar component built using render props, which you can compare with the hooks approach.
Improved TypeScript support
It’s no secret we’re huge fans of TypeScript at Apollo. Combined with automatic type definitions generated by the Apollo CLI, the new hooks make writing type-safe React components even better than before. Here’s what fetching data with Apollo Client’s useQuery and TypeScript looks like: