Leptos-Use Guide

use_debounce_fn

Debounce execution of a function.

Debounce is an overloaded waiter: If you keep asking him your requests will be ignored until you stop and give him some time to think about your latest inquiry.

Demo

Usage

use leptos::*;
use leptos::ev::resize;
use leptos_use::use_debounce_fn;

#[component]
fn Demo() -> impl IntoView {
let mut debounced_fn = use_debounce_fn(
    || {
        // do something
    },
    1000.0,
);

window_event_listener(resize, move |_| { debounced_fn(); });
   view! { }
}

Please note that if the current component is cleaned up before the throttled callback is called, the throttled callback will not be called.

You can also pass options to use_debounce_fn_with_options with a maximum wait time, similar to lodash debounce.

use leptos::*;
use leptos::ev::resize;
use leptos_use::use_debounce_fn_with_options;
use leptos_use::utils::DebounceOptions;

#[component]
fn Demo() -> impl IntoView {
let mut debounced_fn = use_debounce_fn_with_options(
    || {
        // do something
    },
    1000.0,
    DebounceOptions::default()
        .max_wait(Some(5000.0)),
);

window_event_listener(resize, move |_| { debounced_fn(); });
   view! { }
}

Currently there is no way to use a function with a return value. Please open an issue if you need this.

If you want to throttle a function that takes an argument there are also the versions use_debounce_fn_with_arg and use_debounce_fn_with_arg_and_options.

Server-Side Rendering

Internally this uses setTimeout which is not supported on the server. So usually calling a debounced function on the server will simply be ignored.

Feature

This function is only available if the crate feature use_debounce_fn is enabled

Source

SourceDemoDocs