useDebounce hook loses function calls if the dependency changes
Description
If you set a useDebounce with a function callback that can be created with useCallback, If you call the denounced function then the dependencies of the useCallback changes resulting in the useCallback function changing and useDebounce changes also as a result. Because the dependencies of the useDebounced changed the old debounce function calls the cancel method: https://github.com/WordPress/gutenberg/blob/a6d6931245126596851db3dbc26ab987fdfb45fb/packages/compose/src/hooks/use-debounce/index.js#L35. Now the function called never gets called even once.
Step-by-step reproduction instructions
It's easier to show an example of how to replicate this issue: The following code uses a setInterval to simulate users events. This issue does not happen only on interval scenarios like this. A debounce function should be called a minimum of one time otherwise it's not behaving like it should. But if the debounce function is called but the dependency of the useCallback is changed before the debounced function runs you encounter this bug that your event is lost. The following code has two console logs one in the debounced function and one in the interval. The console log from the debounce function never prints.
import { useDebounce } from '@wordpress/compose';
import {
useState,
useCallback,
useRef,
useEffect,
render,
} from '@wordpress/element';
const DebouncePoc = () => {
const [state, setState] = useState(0);
const interval = useRef(null);
const updateStateCallback = useCallback(() => {
const newState = state + 1;
console.log('New state from debounce:', newState);
setState(state + 1);
}, [state]);
const updateStateDebounce = useDebounce(updateStateCallback, 3000);
useEffect(() => {
interval.current = setInterval(() => {
const newState = Math.random();
console.log('New state from interval: ', newState);
updateStateDebounce();
setState(newState);
}, 1000);
return () => {
clearInterval(interval.current);
};
}, []);
return <></>
};
Screenshots, screen recording, code snippet
This is how we solved the issue on our project:
/**
* External dependencies
*/
import { debounce, merge } from 'lodash';
import { useMemoOne } from 'use-memo-one';
/**
* WordPress dependencies
*/
import { useEffect, useRef } from '@wordpress/element';
function useDebounce(fn, wait, options, useDebounceOptions = {}) {
const useDebounceOptionsDefaultOptions = {
flushOnRecreation: true,
cancelOnUnMount: true,
};
const mergedUseDebouncedOptions = merge(
{},
useDebounceOptionsDefaultOptions,
useDebounceOptions
);
const { flushOnRecreation, cancelOnUnMount } = mergedUseDebouncedOptions;
const debounced = useMemoOne(() => debounce(fn, wait, options), [
fn,
wait,
options,
]);
const unmounting = useRef(false);
//hook to know when unmounting
useEffect(() => {
return () => {
unmounting.current = true;
};
}, []);
useEffect(() => {
return () => {
if (cancelOnUnMount && unmounting.current) {
debounced.cancel();
return;
}
if (flushOnRecreation) {
debounced.flush();
} else {
debounced.cancel();
}
};
}, [debounced]);
return debounced;
}
export { useDebounce };
Environment info
No response
Please confirm that you have searched existing issues in the repo.
Yes
Please confirm that you have tested with all plugins deactivated except Gutenberg.
Yes
@ciobanu0151 The 'step-by-step reproduction instructions' is there for you to present a way to reproduce the problem.
That seems to be missing and you've just repeated the description. Please could you fill this part out.
@talldan I updated the bug with a code example on how to replicate the issue and a possible fix for the problem
Thanks!
It's been a while since this issue has been open and there hasn't been much movement. @ciobanu0151 is this issue still persist with the recent version of Gutenberg? If that is the case please feel free to add a note and remove the stale tag 🙇♀️
I was able to reproduce the issue. Here's an example code that can be run in the editor using the browser console.
Snippet:
var { useCallback, useEffect, useState, useRef } = wp.element;
var { useDebounce } = wp.compose;
var { registerPlugin } = wp.plugins;
function DebounceTest() {
const [state, setState] = useState(0);
const interval = useRef(null);
const updateStateCallback = useCallback(() => {
const newState = state + 1;
console.log('New state from debounce:', newState);
setState(state + 1);
}, [state]);
const updateStateDebounce = useDebounce(updateStateCallback, 3000);
useEffect(() => {
interval.current = setInterval(() => {
const newState = Math.random();
console.log('New state from interval: ', newState);
updateStateDebounce();
setState(newState);
}, 1000);
return () => {
clearInterval(interval.current);
};
}, [updateStateDebounce]);
return null;
}
registerPlugin( 'debounce-test-plugin', {
render: DebounceTest,
} );
I'm working on this.
Cause: useDebounce recreates the debounced function whenever fn changes and cancels the old one. With a useCallback whose dependencies change after the debounced function is called, the pending call is dropped and never runs.
Proposed fix: wrap fn with useEvent inside the hook, so the debounced function stays stable but always calls the latest fn. This is the same pattern callers already use as a workaround (useMarkPersistent, media-fields).
Note on the reproduction snippet: the snippet above calls the debounced function every 1s with a 3s wait, so it can never fire with any debounce implementation (lodash included), because every call resets the timer. To show the bug, the interval needs to stop so the debounce has time to fire. Updated snippet (stops after 3 ticks):
Updated reproduction snippet
var { useCallback, useEffect, useState, useRef } = wp.element;
var { useDebounce } = wp.compose;
var { registerPlugin } = wp.plugins;
function DebounceTest() {
const [ state, setState ] = useState( 0 );
const ticks = useRef( 0 );
const updateStateCallback = useCallback( () => {
console.log( 'New state from debounce:', state + 1 );
setState( state + 1 );
}, [ state ] );
const updateStateDebounce = useDebounce( updateStateCallback, 3000 );
useEffect( () => {
const interval = setInterval( () => {
if ( ++ticks.current > 3 ) {
return;
}
const newState = Math.random();
console.log( 'New state from interval:', newState );
updateStateDebounce();
setState( newState );
}, 1000 );
return () => clearInterval( interval );
}, [ updateStateDebounce ] );
return null;
}
registerPlugin( 'debounce-test-plugin', { render: DebounceTest } );
- Current behaviour: three New state from interval logs, then nothing; the debounced callback never runs.
- Expected: New state from debounce is logged ~3s after the last interval tick.
I'll open a PR shortly.