how can i access my queries from react-query?

i’m just begenning 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.

Answer

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 (...)
}