dioxus_hooks/use_callback.rs
1use dioxus_core::prelude::use_hook;
2use dioxus_core::prelude::Callback;
3
4/// Create a callback that's always up to date. Whenever this hook is called the inner callback will be replaced with the new callback but the handle will remain.
5///
6/// There is *currently* no signal tracking on the Callback so anything reading from it will not be updated.
7///
8/// This API is in flux and might not remain.
9#[doc = include_str!("../docs/rules_of_hooks.md")]
10pub fn use_callback<T: 'static, O: 'static>(f: impl FnMut(T) -> O + 'static) -> Callback<T, O> {
11 let mut callback = Some(f);
12
13 // Create a copyvalue with no contents
14 // This copyvalue is generic over F so that it can be sized properly
15 let mut inner = use_hook(|| Callback::new(callback.take().unwrap()));
16
17 if let Some(callback) = callback.take() {
18 // Every time this hook is called replace the inner callback with the new callback
19 inner.replace(Box::new(callback));
20 }
21
22 inner
23}