5

I am trying out React Query for the first time and I wrote this:

export function Component(): JSX.Element {
  const queryClient = new QueryClient()

  const { data } = useQuery<DataType>({
    queryKey: "myKey",
    queryFn: () => ....,
  })

  const sameData: DataType| undefined = queryClient.getQueryData("myKey")

  return (
    <>
      {console.log(data)}
      {console.log(sameData)}
      <p>Loaded, see console for values.</p>
    </>
  )
}

The data object is created as expected, but I cannot seem to make sameData return anything other than undefined. I know this means that React Query isn't finding my key. Does anyone have any ideas on how to fix this?

2 Answers 2

8

You’re creating a new QueryClient in each render, so you’ll get a new cache. Have a look at the example on the front page of the docs: https://react-query.tanstack.com/overview

You need a stable queryClient, and put it in a QueryClientProvider

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! I understand now - super helpful!
Great answer - to add on top of this - make sure the query client is global outside any JSX component or at the root of it. For example on next.js I had the query client inside the Provider function component - while it works during development it breaks on static site generation. Creating the client on the root or simply outside the component solves any issue with it.
in nextjs, if you create the client outside of the component, it will be shared between requests and users on the server. that's why the recommendation with ssr to create it in useState: tanstack.com/query/latest/docs/framework/react/guides/…
6

like the above answer explained

const queryClient = new QueryClient() 

will create a new instance on every render

the provided useQueryClient() hook returns the current instance

const queryClient = useQueryClient()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.