Search code examples
javascriptreact-nativelodashdebouncing

How to debounce multiple clickable buttons


At present I am debouncing using the lodash library like so...

<Button
  onPress={_.debounce(
        () => {
               navigation.goBack()
              },
              500,
              {
                leading: true,
                trailing: false,
               }
   )}
   title="Back"
/>

Which works as expecte when I just click on one link, but if I click on two clickable areas like so... (see below gif) the following happens...

issue


Solution

  • Move definition of debounced function from "render" method, like this:

    export default class YourClassName extends Component {
      constructor() {
        super();
    
        this.debouncedOnPressHandler = _.debounce(
          () => { navigation.goBack() },
          500,
          {
            leading: true,
            trailing: false,
          }
        )
      }
    
      render() {
        return (
          <div>
            <Button onPress={this.debouncedOnPressHandler} title="Back A" />
            <Button onPress={this.debouncedOnPressHandler} title="Back B" />
          </div>
        );
      }
    }