Skip to content

Commit 25e7d7f

Browse files
committed
use TearDown bound instead of FnOnce() for effect hooks
Fixes #61. Replaces the old `Destructor: FnOnce() + 'static` bound with `Destructor: TearDown` on use_effect_once, use_effect_update, and use_effect_update_with_deps, so users no longer need to return `|| ()` when there is no cleanup logic.
1 parent 14b468c commit 25e7d7f

3 files changed

Lines changed: 7 additions & 9 deletions

File tree

crates/yew-hooks/src/hooks/use_effect_once.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ use yew::prelude::*;
2828
pub fn use_effect_once<Callback, Destructor>(callback: Callback)
2929
where
3030
Callback: FnOnce() -> Destructor + 'static,
31-
Destructor: FnOnce() + 'static,
31+
Destructor: TearDown,
3232
{
3333
use_effect_with((), move |_| callback());
3434
}

crates/yew-hooks/src/hooks/use_effect_update.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,6 @@ use super::use_is_first_mount;
1717
/// fn effect_update() -> Html {
1818
/// use_effect_update(|| {
1919
/// debug!("Running effect only on updates");
20-
///
21-
/// || ()
2220
/// });
2321
///
2422
/// html! {
@@ -31,15 +29,16 @@ use super::use_is_first_mount;
3129
pub fn use_effect_update<Callback, Destructor>(callback: Callback)
3230
where
3331
Callback: FnOnce() -> Destructor + 'static,
34-
Destructor: FnOnce() + 'static,
32+
Destructor: TearDown,
3533
{
3634
let first = use_is_first_mount();
3735

3836
use_effect(move || {
3937
if first {
4038
Box::new(|| ()) as Box<dyn FnOnce()>
4139
} else {
42-
Box::new(callback())
40+
let d = callback();
41+
Box::new(move || d.tear_down())
4342
}
4443
});
4544
}
@@ -52,7 +51,7 @@ pub fn use_effect_update_with_deps<Callback, Destructor, Dependents>(
5251
deps: Dependents,
5352
) where
5453
Callback: FnOnce(&Dependents) -> Destructor + 'static,
55-
Destructor: FnOnce() + 'static,
54+
Destructor: TearDown,
5655
Dependents: PartialEq + 'static,
5756
{
5857
let first = use_is_first_mount();
@@ -61,7 +60,8 @@ pub fn use_effect_update_with_deps<Callback, Destructor, Dependents>(
6160
if first {
6261
Box::new(|| ()) as Box<dyn FnOnce()>
6362
} else {
64-
Box::new(callback(deps))
63+
let d = callback(deps);
64+
Box::new(move || d.tear_down())
6565
}
6666
});
6767
}

examples/yew-app/src/app/hooks/use_effect_update.rs

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@ pub fn UseEffectUpdate() -> Html {
1414
let count_effect = count_effect.clone();
1515
use_effect_with(count.clone(), move |_| {
1616
count_effect.set(*count_effect + 1);
17-
|| ()
1817
});
1918
}
2019

@@ -25,7 +24,6 @@ pub fn UseEffectUpdate() -> Html {
2524
use_effect_update_with_deps(
2625
move |_| {
2726
count_effect_update.set(*count_effect_update + 1);
28-
|| ()
2927
},
3028
count,
3129
);

0 commit comments

Comments
 (0)