Skip to main content

ttl

Description: Defines how long the result of a mutation should be kept in the cache. Use -1 for endless caching.

  • How To: Pass ttl (in milliseconds) in the useMutation options. This determines how long the data returned by the hook remains available in the global mutateCache.
    // Correct: Keep mutation result for 1 hour
    const { mutate, data } = useMutation({
    ttl: 60 * 60 * 1000,
    mutationKey: 'last-successful-login'
    });

    const onLogin = () => {
    mutate(() => api.login(credentials));
    };
  • Best Practice: For most standard mutations, the default TTL is sufficient. However, if you need the mutation result to be available globally for an extended period, or if multiple components are observing the same mutationKey, adjusting the ttl ensures the data remains valid and shared correctly.
    // Avoid this: Using ttl: 0 for mutations whose result you need later
    const { mutate, data } = useMutation({
    ttl: 0,
    mutationKey: 'search-results'
    });
    // The data will be immediately stale and potentially cleared from cache!

Deep Dive: How ttl works step by step

Example:

function SearchForm() {
const { mutate, data } = useMutation({
mutationKey: 'global-search',
ttl: 10 * 60 * 1000 // 10 minutes
});

return <button onClick={() => mutate(searchAction)}>Search</button>;
}

function SearchSummary() {
// Another component observing the same mutation
const { data } = useMutation({ mutationKey: 'global-search' });
return <div>Results found: {data?.length ?? 0}</div>;
}

What happens step by step with the timeline:

  1. t=0s: User submits the search form

    • Mutation executes.
    • Result is stored in mutateCache with key 'global-search'.
    • Result expires at: t=0s + 10min = t=10min.
  2. t=2min: User navigates away

    • SearchForm unmounts.
    • Mutation result still exists in the global cache.
  3. t=3min: User navigates back

    • SearchForm mounts again.
    • useMutation checks the cache for 'global-search'.
    • Result is still valid (3min < 10min).
    • data is initialized with the cached value immediately.
  4. t=11min: Component is still mounted

    • Cache checked by internally during re-render or global cleanup.
    • Result is expired (11min > 10min).
    • Cache entry is marked as stale or removed.
    • data may become null upon the next cache validation cycle (depending on keepError or explicit reset).

Key insight: TTL for mutations controls the persistence of the response data in the global cache. This is vital when the result of a mutation needs to be shared across multiple components or must survive navigation.