How can I use react-query in a React class component?

Viewed 5571

I realised: If I want to use hooks import { useQuery } from 'react-query' I can only do that in React function components.

Do I have to rewrite my old class components in the React function syntax, or is there an easy way to use react-query with the class syntax?

I'm sure it's documented somewhere, but I could only find tutorials using React function components.

2 Answers

It’s quite easy to re-implement it with a render props pattern. From a github discussion:

function UseQuery (props) {
  return props.children(useQuery(props.key, props.fn, props.options))
}
<UseQuery
  key=“todos”
  fn={() => getTodos()}
  options={{ staleTime: 5000 }}
>
  {query => {. . .}}
</UseQuery>

Officially hooks (in general) can be only used inside functional React components. See FAQs

You can:

  • rewrite your component (this is probably something that worth it on the long run… there are many other interesting hooks libs out there)
  • try to isolate the code that needs react-query to a functional super-component. This can be hard but it depends on your code. Please note that hooks are not black magic, they are a pattern so it is possible to use them as HOC (Google for "use hooks in class component" and you'll find many examples).
Related