'isLoading' vs 'isFetching' of ReactQuery

React-Query is a powerful tool for facilitating data fetching in modern React applications. I made an interesting discovery while using the keepPreviousData option in React-Query in a recent project. Especially, I realized the importance of understanding the management of isLoading and isFetching states.

isLoading vs isFetching: Understanding the Difference

In React-Query, isLoading is activated when a query is initially executed. This indicates that data has not yet been loaded. On the other hand, isFetching can be activated at any time during the query execution, meaning that data has either already been loaded or is being fetched in the background.

Sharing Experience: The Importance of isFetching When Using keepPreviousData

Activating the keepPreviousData option fetches new data while keeping the previous query data. In this case, using isFetching instead of isLoading is more appropriate. This is because isLoading is only activated during the initial data load, whereas isFetching is also activated during data updates.

Example Code: Using keepPreviousData and isFetching

import { useQuery } from 'react-query';

function MyComponent({ postId }) {
  const { data, isFetching } = useQuery(
    ['post', postId],
    fetchPostById,
    { keepPreviousData: true }
  );

  if (isFetching) return <div>Loading...</div>;

  return (
    <div>
      <h1>{data.title}</h1>
      <p>{data.content}</p>
    </div>
  );
}

async function fetchPostById(postId) {
  const response = await fetch(`https://api.mysite.com/posts/${postId}`);
  return response.json();
}

In the above example, keepPreviousData is used to maintain previous data when a user selects a different post. Simultaneously, isFetching is used to display a loading state while new data is being fetched.

Conclusion

Understanding the difference between isLoading and isFetching when using keepPreviousData in React-Query is important. This understanding helps improve user experience and implement more efficient data fetching strategies.

  • isLoading indicates to the user whether data is being fetched.

  • isFetching indicates in the program whether data is being fetched.

"The difference between the two becomes clear when keepPreviousData is true!"