### Debounce Callback with useDebouncedCallback
Source: https://github.com/xnimorz/use-debounce/blob/master/README.md
Use `useDebouncedCallback` to debounce a function, commonly used with event handlers. The example shows debouncing an input change event to update state after a delay. Ensure to use `e => debounced(e.target.value)` for synthetic events.
```javascript
import { useDebouncedCallback } from 'use-debounce';
function Input({ defaultValue }) {
const [value, setValue] = useState(defaultValue);
// Debounce callback
const debounced = useDebouncedCallback(
// function
(value) => {
setValue(value);
},
// delay in ms
1000
);
// you should use `e => debounced(e.target.value)` as react works with synthetic events
return (
debounced(e.target.value)}
/>
Debounced value: {value}
);
}
```
--------------------------------
### Debounce Scroll Event with useDebouncedCallback
Source: https://github.com/xnimorz/use-debounce/blob/master/README.md
This example demonstrates debouncing a native event listener, specifically a scroll event, using `useDebouncedCallback`. It updates the component's state with the scroll position after a specified delay, preventing excessive re-renders. The `subscribe` function is assumed to be defined elsewhere for handling event listeners and returning an unsubscribe function.
```javascript
function ScrolledComponent() {
// just a counter to show, that there are no any unnessesary updates
const updatedCount = useRef(0);
updatedCount.current++;
const [position, setPosition] = useState(window.pageYOffset);
// Debounce callback
const debounced = useDebouncedCallback(
// function
() => {
setPosition(window.pageYOffset);
},
// delay in ms
800
);
useEffect(() => {
const unsubscribe = subscribe(window, 'scroll', debounced);
return () => {
unsubscribe();
};
}, []);
return (
Debounced top position: {position}
Component rerendered {updatedCount.current} times
);
}
```
--------------------------------
### Leading/Trailing Calls (useDebounce and useDebouncedCallback)
Source: https://github.com/xnimorz/use-debounce/blob/master/README.md
Explains the `leading` and `trailing` options for both `useDebounce` and `useDebouncedCallback`. `leading` executes the function immediately, while `trailing` controls execution after the timeout.
```APIDOC
## leading/trailing calls
Both `useDebounce` and `useDebouncedCallback` work with the `leading` and `trailing` options. `leading` param will execute the function once immediately when called. Subsequent calls will be debounced until the timeout expires. `trailing` option controls whenever to call the callback after timeout again.
For more information on how leading debounce calls work see: https://lodash.com/docs/#debounce
```javascript
import React, { useState } from 'react';
import { useDebounce } from 'use-debounce';
export default function Input() {
const [text, setText] = useState('Hello');
const [value] = useDebounce(text, 1000, { leading: true });
// value is updated immediately when text changes the first time,
// but all subsequent changes are debounced.
return (
{
setText(e.target.value);
}}
/>
Actual value: {text}
Debounce value: {value}
);
}
```
```
--------------------------------
### useDebounce - Advanced Usage (cancel, isPending, flush)
Source: https://github.com/xnimorz/use-debounce/blob/master/README.md
Details the advanced methods available for `useDebounce`: `cancel` to abort pending requests, `isPending` to check for pending requests, and `flush` to immediately execute pending requests.
```APIDOC
The same API is available for `useDebounce` calls:
```js
const [value, {cancel, isPending, flush}] = useDebounce(valueToDebounce);
...
cancel() // cancels pending debounce request
isPending() // returns if there is a pending debouncing request
flush() // immediately flushes pending request
```
```
--------------------------------
### Use Debounce with Leading Option
Source: https://github.com/xnimorz/use-debounce/blob/master/README.md
Shows how to use the `leading: true` option with useDebounce. This executes the function immediately on the first call, then debounces subsequent calls until the timeout expires.
```javascript
import React, { useState } from 'react';
import { useDebounce } from 'use-debounce';
export default function Input() {
const [text, setText] = useState('Hello');
const [value] = useDebounce(text, 1000, { leading: true });
// value is updated immediately when text changes the first time,
// but all subsequent changes are debounced.
return (
{
setText(e.target.value);
}}
/>
Actual value: {text}
Debounce value: {value}
);
}
```
--------------------------------
### useDebouncedCallback - Advanced Usage (maxWait, cancel)
Source: https://github.com/xnimorz/use-debounce/blob/master/README.md
Demonstrates the use of `maxWait` option to set the maximum time a function can be delayed, and the `cancel` callback to stop the debounce cycle.
```APIDOC
## Advanced usage - Cancel, maxWait and memoization
Both `useDebounce` and `useDebouncedCallback` works with `maxWait` option. This params describes the maximum time func is allowed to be delayed before it's invoked.
You can cancel debounce cycle, by calling `cancel` callback
The full example you can see here https://codesandbox.io/s/4wvmp1xlw4
```javascript
import React, { useState } from 'react';
import ReactDOM from 'react-dom';
import { useDebouncedCallback } from 'use-debounce';
function Input({ defaultValue }) {
const [value, setValue] = useState(defaultValue);
const debounced = useDebouncedCallback(
(value) => {
setValue(value);
},
500,
// The maximum time func is allowed to be delayed before it's invoked:
{ maxWait: 2000 }
);
// you should use `e => debounced(e.target.value)` as react works with synthetic events
return (
debounced(e.target.value)}
/>
Debounced value: {value}
);
}
const rootElement = document.getElementById('root');
ReactDOM.render(, rootElement);
```
```
--------------------------------
### Use Debounce with Cancel, IsPending, and Flush
Source: https://github.com/xnimorz/use-debounce/blob/master/README.md
Shows the API for useDebounce, including cancel, isPending, and flush methods. These allow for manual control over pending debounce requests.
```javascript
const [value, {cancel, isPending, flush}] = useDebounce(valueToDebounce);
...
cancel() // cancels pending debounce request
isPending() // returns if there is a pending debouncing request
flush() // immediately flushes pending request
```
--------------------------------
### Use Debounced Callback with IsPending Method
Source: https://github.com/xnimorz/use-debounce/blob/master/README.md
Demonstrates checking the pending state of a debounced callback using the isPending method. It shows how to verify the state before and after invoking and flushing the callback.
```javascript
import React, { useCallback } from 'react';
function Component({ text }) {
const debounced = useDebouncedCallback(
useCallback(() => {}, []),
500
);
expect(debounced.isPending()).toBeFalsy();
debounced();
expect(debounced.isPending()).toBeTruthy();
debounced.flush();
expect(debounced.isPending()).toBeFalsy();
return {text};
}
```
--------------------------------
### isPending Method (useDebounce and useDebouncedCallback)
Source: https://github.com/xnimorz/use-debounce/blob/master/README.md
Describes the `isPending` method, which indicates whether a component has pending callbacks. It works for both `useDebounce` and `useDebouncedCallback`.
```APIDOC
## isPending method
`isPending` method shows whether component has pending callbacks. Works for both `useDebounce` and `useDebouncedCallback`:
```javascript
import React, { useCallback } from 'react';
function Component({ text }) {
const debounced = useDebouncedCallback(
useCallback(() => {}, []),
500
);
expect(debounced.isPending()).toBeFalsy();
debounced();
expect(debounced.isPending()).toBeTruthy();
debounced.flush();
expect(debounced.isPending()).toBeFalsy();
return {text};
}
```
```
--------------------------------
### Import useThrottledCallback Hook
Source: https://github.com/xnimorz/use-debounce/blob/master/README.md
Import the useThrottledCallback hook from the 'use-debounce' library. This hook allows for throttled callback execution.
```javascript
import useThrottledCallback from 'use-debounce/useThrottledCallback';
```
```javascript
import { useThrottledCallback } from 'use-debounce';
```
--------------------------------
### Use Debounced Callback with Flush Method
Source: https://github.com/xnimorz/use-debounce/blob/master/README.md
Illustrates using the flush method of useDebouncedCallback to manually execute a pending callback, useful for scenarios like component unmounting.
```javascript
import React, { useState } from 'react';
import { useDebouncedCallback } from 'use-debounce';
function InputWhichFetchesSomeData({ defaultValue, asyncFetchData }) {
const debounced = useDebouncedCallback(
(value) => {
asyncFetchData;
},
500,
{ maxWait: 2000 }
);
// When the component goes to be unmounted, we will fetch data if the input has changed.
useEffect(
() => () => {
debounced.flush();
},
[debounced]
);
return (
debounced(e.target.value)}
/>
);
}
```
--------------------------------
### useDebouncedCallback - Flush Method
Source: https://github.com/xnimorz/use-debounce/blob/master/README.md
Explains the `flush` method for `useDebouncedCallback`, which allows manual invocation of the callback if it hasn't fired yet, useful for unmounting components.
```APIDOC
## Flush method
`useDebouncedCallback` has `flush` method. It allows to call the callback manually if it hasn't fired yet. This method is handy to use when the user takes an action that would cause the component to unmount, but you need to execute the callback.
```javascript
import React, { useState } from 'react';
import { useDebouncedCallback } from 'use-debounce';
function InputWhichFetchesSomeData({ defaultValue, asyncFetchData }) {
const debounced = useDebouncedCallback(
(value) => {
asyncFetchData;
},
500,
{ maxWait: 2000 }
);
// When the component goes to be unmounted, we will fetch data if the input has changed.
useEffect(
() => () => {
debounced.flush();
},
[debounced]
);
return (
debounced(e.target.value)}
/>
);
}
```
```
--------------------------------
### Use Debounced Callback with MaxWait and Cancel
Source: https://github.com/xnimorz/use-debounce/blob/master/README.md
Demonstrates using useDebouncedCallback with a maxWait option and a cancel button to stop the debounce cycle. Handles synthetic events correctly by passing the event target's value.
```javascript
import React, { useState } from 'react';
import ReactDOM from 'react-dom';
import { useDebouncedCallback } from 'use-debounce';
function Input({ defaultValue }) {
const [value, setValue] = useState(defaultValue);
const debounced = useDebouncedCallback(
(value) => {
setValue(value);
},
500,
// The maximum time func is allowed to be delayed before it's invoked:
{ maxWait: 2000 }
);
// you should use `e => debounced(e.target.value)` as react works with synthetic events
return (
debounced(e.target.value)}
/>
Debounced value: {value}
);
}
const rootElement = document.getElementById('root');
ReactDOM.render(, rootElement);
```
--------------------------------
### Throttle Button Clicks
Source: https://github.com/xnimorz/use-debounce/blob/master/README.md
Use useThrottledCallback to ensure a function is called at most once within a specified interval. The options object can configure behavior like disabling trailing calls.
```javascript
const throttled = useThrottledCallback(renewToken, 300000, { 'trailing': false })
```
--------------------------------
### Throttle Scroll Events
Source: https://github.com/xnimorz/use-debounce/blob/master/README.md
Use useThrottledCallback to limit the rate at which scroll event handlers are called, preventing excessive updates. The second argument is the throttle delay in milliseconds.
```javascript
const scrollHandler = useThrottledCallback(updatePosition, 100);
window.addEventListener('scroll', scrollHandler);
```
--------------------------------
### Debounce Input Value with useDebounce
Source: https://github.com/xnimorz/use-debounce/blob/master/README.md
Use `useDebounce` to debounce the state of an input field. The hook compares previous and next values using shallow equality, triggering the debounce timer if they differ. For object comparisons, consider `useDebouncedCallback`.
```javascript
import React, { useState } from 'react';
import { useDebounce } from 'use-debounce';
export default function Input() {
const [text, setText] = useState('Hello');
const [value] = useDebounce(text, 1000);
return (
{
setText(e.target.value);
}}
/>
Actual value: {text}
Debounce value: {value}
);
}
```
--------------------------------
### Test Debounced Callback Return Value
Source: https://github.com/xnimorz/use-debounce/blob/master/README.md
Tests that subsequent calls to a debounced function return the result of the last invocation. Returns undefined if there are no previous invocations.
```javascript
it('Subsequent calls to the debounced function `debounced` return the result of the last func invocation.', () => {
const callback = jest.fn(() => 42);
let callbackCache;
function Component() {
const debounced = useDebouncedCallback(callback, 1000);
callbackCache = debounced;
return null;
}
Enzyme.mount();
const result = callbackCache();
expect(callback.mock.calls.length).toBe(0);
expect(result).toBeUndefined();
act(() => {
jest.runAllTimers();
});
expect(callback.mock.calls.length).toBe(1);
const subsequentResult = callbackCache();
expect(callback.mock.calls.length).toBe(1);
expect(subsequentResult).toBe(42);
});
```
--------------------------------
### useDebouncedCallback - Returned Value
Source: https://github.com/xnimorz/use-debounce/blob/master/README.md
Subsequent calls to the debounced function return the result of the last func invocation. If there are no previous invocations, it returns undefined.
```APIDOC
## Returned value from `debounced()`
Subsequent calls to the debounced function `debounced` return the result of the last func invocation. Note, that if there are no previous invocations it's mean you will get undefined. You should check it in your code properly.
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.