I would like to use lodash debounce
to prevent a button onClick from being run more than once in the event of multiple, rapid clicks. The button is in stateless functional component and from what I've read (in this SO question), debounce
will not work in functional components due the debounced function being new each render.
One way to solve this seems to be to use the useCallback
react hook but, unfortunately, the project is currently at react version 15.6.1 and it is not feasible to upgrade at this time. I can also get debounce
to work if I convert the component to a stateful component or if I pass in an already debounced submit function, but I think the best case outcome would be maintaining the functional component while still having it be able to protect against multiple submissions for any submit function.
Is it possible to get debounce to work inside a functional component without using hooks?
Here is my functional component for which debounce isn't working:
import * as React from 'react';
import * as Lodash from 'lodash';
import { Button } from 'react-bootstrap';
import { Modal } from 'react-bootstrap';
export const ConfirmSubmitModal = props => {
const { submit } = props;
const debouncedSubmit = Lodash.debounce(() => {
submit();
}, 3000, { "leading": true, "trailing": false });
return (
<div>
<Modal>
<Button onClick={debouncedSubmit}>Submit</Button>
</Modal>
</div>
);
};