RTK Query can start fetching data in your application before React is even available. This can be handy when your application relies heavily on data that you need to fetch. This data is cached so your users won't be refetching this data when they navigate through out the application.
Prefetching relies on the powerful api.endpoints.<queryName>.initiate()
method that underlies much RTK Query's internals. For RTK Query to process and store initiate() calls properly they have to be sent into the redux store with store.dispatch()
.
An advanced variation of this splits your main app file into the data pre-fetching (done first) and then your react application (lazy-loaded with import()
). The idea being that you want to start your data calls before JS has to even start process what's likely to be a large bundle file.
For more information about prefetching with RTK Qyery see: https://redux-toolkit.js.org/rtk-query/usage/prefetching#prefetching-without-hooks.
Instructor: [0:00] If your application relies on network data to render, you'll want to start fetching data as soon as possible. Oftentimes even before you start rendering your application with React. Well, RTK Query has a hard dependency on Redux. Its queries can be initiated without React or custom hooks.
[0:16] Over in your main.jsx file, import API from store/apiSlice. Then before we even start React, type store.dispatch(api.endpoints.getDogs.initiate). This will actually kick off the getDogs query. Let's open up the website and start at the home page. You'll now see that it's calling the dogs API even before I hit the page that needs it.
[0:42] Let's do the same thing for services. We can call store.dispatch(api.endpoints.getServices.initiate). After saving that, if you reload the page, you'll see that no matter where you start, whether you're on contact or home, it's always going to call both the dogs and services APIs to kick-start that data fetch immediately.
[1:03] Just to show how to add in an argument, type store.dispatch(api.endpoints.getService.initiate) and let's pass in the ID a098239. So that's going to prefetch service with the ID a098239. Sure enough, you can see that that happens here and it actually gets cached properly.
[1:27] Now, here's the interesting thing. Even though we kickstarted those routes, it doesn't mean that it's going to be fetching that data again. In fact, it's cached. When we go into the services page or the My Dogs page, it's not going to re-ask for that data. We just ask for it earlier.
[1:41] If you can anticipate which calls are most important to load your site, it's very useful to start loading that data as early as possible.