React Query one loading spinner for 3 child components

Viewed 31

I have three components, each using the same two queries (custom hooks):

  const {
    data: survey,
    isLoading: isSurveyLoading,
    isError: isSurveyError,
  } = useSurveyInfo(id);

  const {
    data: responses,
    isLoading: isResponsesLoading,
    isError: isResponsesError,
  } = useResponses(id);

In each of these 3 components, I'm showing a loading spinner in the case of isLoading loading spinners

How do I show one loading spinner for all three components?

I know I could use the queries in the parent component and pass props to children. But to eliminate prop drilling, I am calling each query in the child component (which seems to be best practice).

Is there a way to show one loading spinner when any of the 3 child components is loading?

3 Answers

One of beauties of react-quiry is that it allows you to render multiple components that relay on the same data and updates all the components at the same time since they all rely on the same provider.

But now the job to make it look good on the website is on us.

I suggest not rendering the loader from the 2 lower components in the page. Or if it makes no sense to have a content less component, you can always return null from the components.

const SecondAndTheirComponents = () => {
  const { isLoading: isResponsesLoading } = useResponses(id);

  if (isResponsesLoading) {
    return null;
  }
  return (
    <Content
      ...
     />
  );
};

Or better yet. I would recomment looking into adding skeletons why you are loading data. This way you could save the space for all component and avoid jumpiness when data is returned to the browser.

You can checkout the skeletons by Material-ui (both v3 and v4 work perfectly fro me) v4 skeletons-material

According to your first question loading one spinner for all three components, you can use if else condition of reactjs, for example-

{
isResponseLoading?
isSurveyLoading?
<RunSpinnerCode/>
:
null
}

As shown in the above we can check two and even more condition. If first one is loaded, then we check for second one and so on.. Hope you like the answer if you still face any issue, just lemme know. Thanks

Related