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