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