clearOnRefetch
Description: Defines if the cache entry should be deleted before being refetched.
Default Value: true.
- How To: Use
clearOnRefetch: truewhen you want to ensure the UI immediately reflects a loading state before new data arrives, rather than showing stale data. This can be useful for critical updates where showing outdated information is undesirable. Clearing cache might cause UI flicker if not handled gracefully. Therefore usingisLoadingstate to show a<LoadingSpinner/>can lead to a better user experience.// Correct: Clear cache to show immediate loading state on refetchconst { data, isLoading } = useFetch('important-data',() => fetchImportantData(),{ clearOnRefetch: true } // UI will show loading indicator during refetch);if (isLoading) return <LoadingSpinner />;return (<div><Component data={data} /></div>); - How To: Use
clearOnRefetch: false(default) if you prefer to show stale data while refetching. This helps to prevent UI flickering.// Stale user feed data will be shown till new data is fetcheduseFetch('user-feed',() => fetchUserFeed(),{ clearOnRefetch: false });
note
Note that isLoading will always be false if suspense: true is set in the options. This is because the component suspends (throws a Promise) during the fetching state before it can return isLoading: true. In this case, you must use a Suspense boundary with a fallback to show the loading state.
- How To: When using
suspense: truewithclearOnRefetch: true, the component will suspend on every refetch. You must wrap the component with aSuspenseboundary to handle the loading state.// Component using suspenseconst { data } = useFetch('important-data',() => fetchImportantData(),{ clearOnRefetch: true, suspense: true });return <Component data={data} />;// Usage in parent<Suspense fallback={<LoadingSpinner />}><MyComponent /></Suspense>