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

useDebouncer.md

146 lines4.5 KB

1---
2id: useDebouncer
3title: useDebouncer
4---
5​
6```ts
7function useDebouncer<TFn, TSelected>(
8 fn,
9 options,
10selector?): ReactDebouncer<TFn, TSelected>;
11```
12​
13Defined in: [debouncer/useDebouncer.ts:163](https://github.com/TanStack/pacer/blob/main/packages/react-pacer/src/debouncer/useDebouncer.ts#L163)
14​
15A React hook that creates and manages a Debouncer instance.
16​
17This is a lower-level hook that provides direct access to the Debouncer's functionality without
18any built-in state management. This allows you to integrate it with any state management solution
19you prefer (useState, Redux, Zustand, etc.).
20​
21This hook provides debouncing functionality to limit how often a function can be called,
22waiting for a specified delay before executing the latest call. This is useful for handling
23frequent events like window resizing, scroll events, or real-time search inputs.
24​
25The debouncer will only execute the function after the specified wait time has elapsed
26since the last call. If the function is called again before the wait time expires, the
27timer resets and starts waiting again.
28​
29## State Management and Selector
30​
31The hook uses TanStack Store for reactive state management. You can subscribe to state changes
32in two ways:
33​
34**1. Using `debouncer.Subscribe` HOC (Recommended for component tree subscriptions)**
35​
36Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without
37needing to pass a selector to the hook. This is ideal when you want to subscribe to state
38in child components.
39​
40**2. Using the `selector` parameter (For hook-level subscriptions)**
41​
42The `selector` parameter allows you to specify which state changes will trigger a re-render
43at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant
44state changes occur.
45​
46**By default, there will be no reactive state subscriptions** and you must opt-in to state
47tracking by providing a selector function or using the `Subscribe` HOC. This prevents unnecessary
48re-renders and gives you full control over when your component updates.
49​
50Available state properties:
51- `canLeadingExecute`: Whether the debouncer can execute on the leading edge
52- `executionCount`: Number of function executions that have been completed
53- `isPending`: Whether the debouncer is waiting for the timeout to trigger execution
54- `lastArgs`: The arguments from the most recent call to maybeExecute
55- `status`: Current execution status ('disabled' | 'idle' | 'pending')
56​
57## Unmount behavior
58​
59By default, the hook cancels any pending execution when the component unmounts.
60Use the `onUnmount` option to customize this. For example, to flush pending work instead:
61​
62```tsx
63const debouncer = useDebouncer(fn, {
64 wait: 500,
65 onUnmount: (d) => d.flush()
66});
67```
68​
69## Type Parameters
70​
71### TFn
72​
73`TFn` *extends* `AnyFunction`
74​
75### TSelected
76​
77`TSelected` = \{
78\}
79​
80## Parameters
81​
82### fn
83​
84`TFn`
85​
86### options
87​
88[`ReactDebouncerOptions`](../interfaces/ReactDebouncerOptions.md)\<`TFn`, `TSelected`\>
89​
90### selector?
91​
92(`state`) => `TSelected`
93​
94## Returns
95​
96[`ReactDebouncer`](../interfaces/ReactDebouncer.md)\<`TFn`, `TSelected`\>
97​
98## Example
99​
100```tsx
101// Default behavior - no reactive state subscriptions
102const searchDebouncer = useDebouncer(
103 (query: string) => fetchSearchResults(query),
104 { wait: 500 }
105);
106​
107// Subscribe to state changes deep in component tree using Subscribe HOC
108<searchDebouncer.Subscribe selector={(state) => ({ isPending: state.isPending })}>
109 {({ isPending }) => (
110 <div>{isPending ? 'Searching...' : 'Ready'}</div>
111 )}
112</searchDebouncer.Subscribe>
113​
114// Opt-in to re-render when isPending changes at hook level (optimized for loading states)
115const searchDebouncer = useDebouncer(
116 (query: string) => fetchSearchResults(query),
117 { wait: 500 },
118 (state) => ({ isPending: state.isPending })
119);
120​
121// Opt-in to re-render when executionCount changes (optimized for tracking execution)
122const searchDebouncer = useDebouncer(
123 (query: string) => fetchSearchResults(query),
124 { wait: 500 },
125 (state) => ({ executionCount: state.executionCount })
126);
127​
128// Multiple state properties - re-render when any of these change
129const searchDebouncer = useDebouncer(
130 (query: string) => fetchSearchResults(query),
131 { wait: 500 },
132 (state) => ({
133 isPending: state.isPending,
134 executionCount: state.executionCount,
135 status: state.status
136 })
137);
138​
139// In an event handler
140const handleChange = (e) => {
141 searchDebouncer.maybeExecute(e.target.value);
142};
143​
144// Access the selected state (will be empty object {} unless selector provided)
145const { isPending } = searchDebouncer.state;
146```