Writing Custom React Hooks for GraphQL
How to create custom React hooks to handle common GraphQL operations.
With the recent release of the new React APIs at React Conf 2018 there has been a flurry of discussion & open source libraries created around the new opportunities that hooks have made available to React developers.
When hooks first came out, I had a question:
What I learned was that, at their core, hooks allow developers to do 2 things that either were not possible before without an additional library or that were much more difficult before the new API was created:
- Use state within a functional React component.
- Make shared behaviors across different components into a hook, that you previously could not really refactor into shared code.
Because I’ve been working a lot with GraphQL (specifically AWS AppSync), I immediately thought of using hooks to more easily set up GraphQL subscriptions: