You are currently viewing the docs for Dioxus 0.5.7 which is no longer maintained.

Routing Update Callback

In some cases, we might want to run custom code when the current route changes. For this reason, the RouterConfig exposes an on_update field.

How does the callback behave?

The on_update is called whenever the current routing information changes. It is called after the router updated its internal state, but before dependent components and hooks are updated.

If the callback returns a NavigationTarget, the router will replace the current location with the specified target. It will not call the on_update again.

If at any point the router encounters a navigation failure, it will go to the appropriate state without calling the on_update. It doesn't matter if the invalid target initiated the navigation, was found as a redirect target, or was returned by the on_update itself.

Code Example

src/routing_update.rs
#[derive(Routable, Clone, PartialEq)]
enum Route {
    #[route("/")]
    Index {},
    #[route("/home")]
    Home {},
}

#[component]
fn Home() -> Element {
    rsx! { p { "Home" } }
}

#[component]
fn Index() -> Element {
    rsx! { p { "Index" } }
}

fn app() -> Element {
    rsx! {
        Router::<Route> {
            config: || {
                RouterConfig::default()
                    .on_update(|state| {
                        (state.current() == Route::Index {})
                            .then_some(NavigationTarget::Internal(Route::Home {}))
                    })
            }
        }
    }
}