Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

usePacedMutations.ts

138 lines4.2 KB

1import { useCallback, useMemo, useRef } from 'react'
2import { createPacedMutations } from '@tanstack/db'
3import type { PacedMutationsConfig, Transaction } from '@tanstack/db'
4​
5/**
6 * React hook for managing paced mutations with timing strategies.
7 *
8 * Provides optimistic mutations with pluggable strategies like debouncing,
9 * queuing, or throttling. The optimistic updates are applied immediately via
10 * `onMutate`, and the actual persistence is controlled by the strategy.
11 *
12 * @param config - Configuration including onMutate, mutationFn and strategy
13 * @returns A mutate function that accepts variables and returns Transaction objects
14 *
15 * @example
16 * ```tsx
17 * // Debounced auto-save
18 * function AutoSaveForm({ formId }: { formId: string }) {
19 * const mutate = usePacedMutations<string>({
20 * onMutate: (value) => {
21 * // Apply optimistic update immediately
22 * formCollection.update(formId, draft => {
23 * draft.content = value
24 * })
25 * },
26 * mutationFn: async ({ transaction }) => {
27 * await api.save(transaction.mutations)
28 * },
29 * strategy: debounceStrategy({ wait: 500 })
30 * })
31 *
32 * const handleChange = async (value: string) => {
33 * const tx = mutate(value)
34 *
35 * // Optional: await persistence or handle errors
36 * try {
37 * await tx.isPersisted.promise
38 * console.log('Saved!')
39 * } catch (error) {
40 * console.error('Save failed:', error)
41 * }
42 * }
43 *
44 * return <textarea onChange={e => handleChange(e.target.value)} />
45 * }
46 * ```
47 *
48 * @example
49 * ```tsx
50 * // Throttled slider updates
51 * function VolumeSlider() {
52 * const mutate = usePacedMutations<number>({
53 * onMutate: (volume) => {
54 * settingsCollection.update('volume', draft => {
55 * draft.value = volume
56 * })
57 * },
58 * mutationFn: async ({ transaction }) => {
59 * await api.updateVolume(transaction.mutations)
60 * },
61 * strategy: throttleStrategy({ wait: 200 })
62 * })
63 *
64 * return <input type="range" onChange={e => mutate(+e.target.value)} />
65 * }
66 * ```
67 *
68 * @example
69 * ```tsx
70 * // Debounce with leading/trailing for color picker (persist first + final only)
71 * function ColorPicker() {
72 * const mutate = usePacedMutations<string>({
73 * onMutate: (color) => {
74 * themeCollection.update('primary', draft => {
75 * draft.color = color
76 * })
77 * },
78 * mutationFn: async ({ transaction }) => {
79 * await api.updateTheme(transaction.mutations)
80 * },
81 * strategy: debounceStrategy({ wait: 0, leading: true, trailing: true })
82 * })
83 *
84 * return (
85 * <input
86 * type="color"
87 * onChange={e => mutate(e.target.value)}
88 * />
89 * )
90 * }
91 * ```
92 */
93export function usePacedMutations<
94 TVariables = unknown,
95 T extends object = Record<string, unknown>,
96>(
97 config: PacedMutationsConfig<TVariables, T>,
98): (variables: TVariables) => Transaction<T> {
99 // Keep refs to the latest callbacks so we can call them without recreating the instance
100 const onMutateRef = useRef(config.onMutate)
101 onMutateRef.current = config.onMutate
102​
103 const mutationFnRef = useRef(config.mutationFn)
104 mutationFnRef.current = config.mutationFn
105​
106 // Create stable wrappers that always call the latest version
107 const stableOnMutate = useCallback<typeof config.onMutate>((variables) => {
108 return onMutateRef.current(variables)
109 }, [])
110​
111 const stableMutationFn = useCallback<typeof config.mutationFn>((params) => {
112 return mutationFnRef.current(params)
113 }, [])
114​
115 // Create paced mutations instance with proper dependency tracking
116 // Serialize strategy for stable comparison since strategy objects are recreated on each render
117 const mutate = useMemo(() => {
118 return createPacedMutations<TVariables, T>({
119 ...config,
120 onMutate: stableOnMutate,
121 mutationFn: stableMutationFn,
122 })
123 }, [
124 stableOnMutate,
125 stableMutationFn,
126 config.metadata,
127 // Serialize strategy to avoid recreating when object reference changes but values are same
128 JSON.stringify({
129 type: config.strategy._type,
130 options: config.strategy.options,
131 }),
132 ])
133​
134 // Return stable mutate callback
135 const stableMutate = useCallback(mutate, [mutate])
136​
137 return stableMutate