reactjsaxiosreact-query

Access data already fetched with react query in other component


I'm new with React Query, and I have a question, I've being looking on the documentation but I can't find how should I access the data that is already fetched with useQuery() from another component.

I'm fetching const query = useQuery('todos', fetchFunction) from HomeComponent and I want to access that data that is already fetched in the TodosComponent. Is ok to fetch the data again with const query = useQuery('todos', fetchFunction) or is there anything like redux that the data is in something like Store so I can access it from any place ?

;)


Solution

  • It is definitely best to just call useQuery again, because it's the only thing that creates a subscription, so your component will re-render correctly if new data comes in. You can do it imperatively with queryClient.getQueryData('todos'), but it doesn't create a subscription.

    Note that useQuery will not always trigger a fetch of the data. You can customize staleTime to tell react-query how long a resource is considered fresh, and as long as it's fresh, data will come from the internal cache only. If you set staleTime: Infinity, there will only be one fetch, and all other invocations will only read from the cache (apart from manual invalidations and garbage collection).

    It's also best to extract useQuery calls to a custom hook:

    const useTodos = () => useQuery('todos', fetchFunction)
    
    HomeComponent:
    
    const { data } = useTodos()
    
    TodosComponent:
    
    const { data } = useTodos()