Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 602
bodison Avatar asked May 18 '26 18:05

bodison


1 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>
like image 82
TkDodo Avatar answered May 22 '26 00:05

TkDodo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!