Create a Custom React Hook Using Gatsby’s useStaticQuery to Query Custom Sourced Data

Colby Fayock
InstructorColby Fayock

Share this video with your friends

Send Tweet
Published 2 years ago
Updated a year ago

In this lesson, we'll create a new custom React Hook that we'll use to make a GraphQL query to request data that we custom sourced from the PokeAPI. We'll walk through migrating our useStateQuery Gatsby hook to our new custom hook, configuring our output of the custom hook, and using it to access our custom sourced data.

Colby Fayock: [0:00] We're going to start off with a Gatsby site that we turned into a Pokedex. Here we're custom sourcing data from the PokeAPI. We're using Gatsby's useStaticQuery and GraphQL, in order to query that data for our page.

[0:09] With that data, we're creating a new list item for each Pokemon. Using the useStaticQuery hook on the page is a great solution. It makes it easy to grab our GraphQL data right on that page. What if he wanted to use that data on another page? We would either have to copy and paste this snippet, or we can create a custom hook.

[0:23] We're going to start off creating a custom hook by creating a new folder under src called hooks. In that folder, we're going to create a new file called usePokemon.js. To create our hook, we're going to start off by defining a new export. We're going to make it our default export and we're going to call that function usePokemon.

[0:37] At the top of that file, we're going to start off by importing our { useStaticQuery, graphql } from 'gatsby'. For the contents of the page, we're going to go back to our index file. We're going to copy all of our existing Pokemon logic and we're going to paste it in right to that file.

[0:50] The only difference is we're going to rename allPokemon to just Pokemon. That way we can create our return statement and simply include Pokemon. To use that file, we're first going to need to import it. We're going to import usePokemon from 'hooks/usePokemon'. With our hook imported, we can destructure our Pokemon from usePokemon.

[1:06] To test this out, we can console.log out that Pokemon. If we look at our browser, we can see the Pokemon data that we get from our hook. Now that we're using our hook, we can get rid of all of our original logic.

[1:14] Since we're already using allPokemon in our map, we can rename our Pokemon to allPokemon. Now, if we reload the page, we can see that it's successfully listing out our Pokemon, but now we're using our custom book.

[1:24] In review, we were using useStaticQuery right on our home page to list out all of our Pokemon. To make that code easier to maintain, and so that we can use it in other places, we created a custom hook called usePokemon.

[1:33] On our home page, we imported that hook and used it for our data. Since we were already mapping through all that data and listing it out, we were still able to see all of our Pokemon data but from using our custom hook.