dioxus_lib::prelude

Function use_drop

source
pub fn use_drop<D>(destroy: D)
where D: FnOnce() + 'static,
Expand description

Creates a callback that will be run before the component is removed. This can be used to clean up side effects from the component (created with use_effect).

Note: Effects do not run on the server, but use_drop DOES. It runs any time the component is dropped including during SSR rendering on the server. If your clean up logic targets web, the logic has to be gated by a feature, see the below example for details.

Example:

use dioxus::prelude::*;

fn app() -> Element {
    let mut state = use_signal(|| true);
    rsx! {
        for _ in 0..100 {
            h1 {
                "spacer"
            }
        }
        if state() {
            child_component {}
        }
        button {
            onclick: move |_| {
                state.toggle()
            },
            "Unmount element"
        }
    }
}

fn child_component() -> Element {
    let mut original_scroll_position = use_signal(|| 0.0);

    use_effect(move || {
        let window = web_sys::window().unwrap();
        let document = window.document().unwrap();
        let element = document.get_element_by_id("my_element").unwrap();
        element.scroll_into_view();
        original_scroll_position.set(window.scroll_y().unwrap());
    });

    use_drop(move || {
        // This only make sense to web and hence the `web!` macro
        web! {
            /// restore scroll to the top of the page
            let window = web_sys::window().unwrap();
            window.scroll_with_x_and_y(original_scroll_position(), 0.0);
        }
    });

    rsx! {
        div {
            id: "my_element",
            "hello"
        }
    }
}