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 theuseMutationoptions. This determines how long thedatareturned by the hook remains available in the globalmutateCache.// Correct: Keep mutation result for 1 hourconst { 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 thettlensures the data remains valid and shared correctly.// Avoid this: Using ttl: 0 for mutations whose result you need laterconst { 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:
-
t=0s: User submits the search form
- Mutation executes.
- Result is stored in
mutateCachewith key'global-search'. - Result expires at:
t=0s + 10min = t=10min.
-
t=2min: User navigates away
SearchFormunmounts.- Mutation result still exists in the global cache.
-
t=3min: User navigates back
SearchFormmounts again.useMutationchecks the cache for'global-search'.- Result is still valid (3min < 10min).
datais initialized with the cached value immediately.
-
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.
datamay becomenullupon the next cache validation cycle (depending onkeepErroror 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.