react-query - How can I access my queries in multiple components?

I'm just beginning with react query and used it to get a list of books from the server using useQuery in my ListBooks Component

const { data, error, isLoading, isError } = useQuery("books", getAllBooks);

How can I access the list of books in any other component?

I've setted the QueryClientProvider like so :

 const queryCache = new QueryCache({
  onError: (error) => {
    console.log(error);
  },
});

const queryClient = new QueryClient({ queryCache });

ReactDOM.render(
  <React.StrictMode>
    <QueryClientProvider client={queryClient}>
      <ThemeProvider theme={preset}>
        <BrowserRouter>
          <App />
        </BrowserRouter>
      </ThemeProvider>
      <ReactQueryDevtools initialIsOpen={false} />
    </QueryClientProvider>
  </React.StrictMode>,
  document.getElementById("root")
);

I'm searching for the equivalent of useSelector in Redux to access the data in the redux store.


Solution 1:

react-query manages query caching based on query keys, so in the other component, as long as they're all wrapped inside QueryClientProvider, you just need to call useQuery with the matching key (books), and react-query will return the appropriate data for you.

If you use the same query in multiple places, consider adding a wrapper hook to keep your code clean:

function useAllBooks() {
  return useQuery("books", getAllBooks)
}
function Component1() {
  const {...} = useAllBooks()
  return (...)
}

function Component2() {
  const {...} = useAllBooks()
  return (...)
}