Backbencher.dev

Share Query Across Components Using Hooks in React Query

Last updated on 9 Aug, 2021

We can share a Query across components using React hooks. Here is an example of a custom React hook that fetch data from Github API.

const useGitUsers = () => {
  return useQuery("gitUsers", () => {
    return fetch("https://api.github.com/search/users?q=joby&per_page=10").then(
      (res) => res.json()
    );
  });
};

The hook returns a query. The hook can now be reused in functional components.

function ShowCount() {
  const queryUsers = useGitUsers();

  // Show results count from queryUsers.data.total_count
}

function GitUsers() {
  const queryUsers = useGitUsers();

  // Loop through queryUsers.data.items to show users list
}

Here, since both components are using the same query, only one network call happens.

--- ○ ---
Joby Joseph
Web Architect