new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Redux Toolkit · RTK Query · all subjects

cache-management/prefetch

21 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

prefetch example

Example: dispatch(api.util.prefetch('getPosts', undefined, { force: true }))

prefetch signature and parameters

prefetch is a Redux thunk action creator with signature: type PrefetchOptions = { ifOlderThan?: false | number } | { force?: boolean }; const prefetch = (endpointName: string, arg: any, options: PrefetchOptions) => ThunkAction<void, any, any, UnknownAction>. Parameters are: endpointName (a string matching an existing endpoint name), args (a cache key, used to determine which cached dataset needs to be updated), options (options to determine whether the request should be sent: ifOlderThan runs the query only if the difference between new Date() and the last fulfilledTimeStamp is greater than the given value in seconds, force if true ignores the ifOlderThan value and runs the query even if it exists in the cache).

prefetch usage and React Hooks

React Hooks users will most likely never need to use prefetch directly, as the usePrefetch hook will dispatch the thunk action creator result internally as needed when you call the prefetching function supplied by the hook.

usePrefetch hook signature and parameters

usePrefetch accepts endpointName (string name of endpoint to prefetch) and optional UsePrefetchOptions. UsePrefetchOptions are either {ifOlderThan?: false | number} to run query only if difference between new Date() and last fulfilledTimeStamp is greater than given seconds value, or {force?: boolean} to ignore ifOlderThan and run query even if in cache. Returns PrefetchCallback function.

usePrefetch callback signature

PrefetchCallback accepts arg (any) and optional UsePrefetchOptions and returns void. When called, it initiates fetching data for the provided endpoint with manual control over whether the request fires based on cache age.

RTK Query supports prefetching

RTK Query supports prefetching to load data before it is needed.

usePrefetch ifOlderThan true behavior

If ifOlderThan is specified and evaluates to true, the query will be performed even if there is an existing cache entry. If a useQuery hook in the tree is subscribed to the same query being prefetched, useQuery will return {isLoading: false, isFetching: true, ...rest}.

Prefetching purpose and use cases

Prefetching is designed to fetch data before the user navigates to a page or attempts to load known content. Common use cases include: user hovers over a navigation element, user hovers over a list element that is a link, user hovers over a next pagination button, or user navigates to a page where components down the tree will require data, preventing fetching waterfalls.

Prefetching vs subscriptions differences

Prefetching is a fire and forget operation that loads data into cache without creating an ongoing subscription. This means: no automatic refetching when tags are invalidated, no subscription management needed, prefetched data without active subscriptions may be removed during cache cleanup, and the prefetch trigger function returns void (not a promise or subscription handle).

When to use prefetch vs query hooks

Use prefetch when you want to load data ahead of time (e.g., on hover) but don't need it to stay fresh. Use query hooks like useQuery or useQuerySubscription when you need data that automatically refetches on invalidation and stays in cache while the component is mounted. You can use both together: prefetch on hover, then let the query hook create a subscription when the user navigates.

usePrefetch hook signature and parameters

The usePrefetch hook accepts two arguments: the first is the key of a query action defined in the API service, and the second is an optional object with two optional parameters. The hook returns a trigger function with signature: usePrefetch<EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, options?: PrefetchOptions) => (arg: QueryArgFrom<Definitions[EndpointName]>, options?: PrefetchOptions) => void. PrefetchOptions can be either { force?: boolean } or { ifOlderThan?: false | number }.

usePrefetch trigger function always returns void

The trigger function returned by usePrefetch always returns void, never a promise or subscription handle.

usePrefetch force option behavior

If force: true is set during declaration or at the call site, the query will be run no matter what. The one exception is if the same query is already in-flight, in which case it will not be run again.

usePrefetch no options behavior with cached query

If no options are specified and the query exists in the cache, the query will not be performed.

usePrefetch no options behavior with uncached query

If no options are specified and the query does not exist in the cache, the query will be performed. If a useQuery hook in the tree is subscribed to the same query being prefetched, useQuery will return {isLoading: true, isFetching: true, ...rest}.

usePrefetch ifOlderThan false behavior

If ifOlderThan is specified but evaluates to false and the query is in the cache, the query will not be performed.

usePrefetch example with options

function User() { const prefetchUser = usePrefetch('getUser') return ( <div> <button onMouseEnter={() => prefetchUser(4, { ifOlderThan: 35 })}> Low priority </button> <button onMouseEnter={() => prefetchUser(4, { force: true })}> High priority </button> </div> ) } This example shows low priority hover that will not fire unless the last request happened more than 35 seconds ago, and high priority hover that will always fire.

Recipe: usePrefetchImmediately hook

type EndpointNames = keyof typeof api.endpoints export function usePrefetchImmediately<T extends EndpointNames>( endpoint: T, arg: Parameters<(typeof api.endpoints)[T]['initiate']>[0], options: PrefetchOptions = {}, ) { const dispatch = useAppDispatch() useEffect(() => { dispatch(api.util.prefetch(endpoint, arg as any, options)) }, []) } // In a component usePrefetchImmediately('getUser', 5) This pattern prefetches a resource immediately when the component mounts.

Prefetching without hooks using api.util.prefetch

You can recreate prefetch behavior in any framework without the usePrefetch hook by dispatching the prefetch thunk. The behavior will be the same as described in trigger function behavior. Syntax: store.dispatch(api.util.prefetch(endpointName, arg, { force: false, ifOlderThan: 10 }))

api.util.prefetch vs endpoint.initiate() differences

api.util.prefetch() automatically uses subscribe: false with no cleanup needed and is designed for simple load and forget scenarios. endpoint.initiate() defaults to subscribe: true, requires manual unsubscribe() call for cleanup, and should only be used when you need fine-grained control over subscriptions and are prepared to manage the subscription lifecycle yourself.

endpoint.initiate() example with manual unsubscribe

// This creates a subscription that must be manually cleaned up const promise = dispatch( api.endpoints[endpointName].initiate(arg, { subscribe: true, // Creates a subscription (default) forceRefetch: true, }), ) // You must manually unsubscribe to prevent memory leaks promise.unsubscribe() This example shows how initiate() requires explicit subscription management that prefetch() does not.

Give your agent this brain