yew/functional/hooks/use_effect.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
use std::cell::RefCell;
use crate::functional::{hook, Effect, Hook, HookContext};
/// Trait describing the destructor of [`use_effect`] hook.
pub trait TearDown: Sized + 'static {
/// The function that is executed when destructor is called
fn tear_down(self);
}
impl TearDown for () {
fn tear_down(self) {}
}
impl<F: FnOnce() + 'static> TearDown for F {
fn tear_down(self) {
self()
}
}
struct UseEffectBase<T, F, D>
where
F: FnOnce(&T) -> D + 'static,
T: 'static,
D: TearDown,
{
runner_with_deps: Option<(T, F)>,
destructor: Option<D>,
deps: Option<T>,
effect_changed_fn: fn(Option<&T>, Option<&T>) -> bool,
}
impl<T, F, D> Effect for RefCell<UseEffectBase<T, F, D>>
where
F: FnOnce(&T) -> D + 'static,
T: 'static,
D: TearDown,
{
fn rendered(&self) {
let mut this = self.borrow_mut();
if let Some((deps, runner)) = this.runner_with_deps.take() {
if !(this.effect_changed_fn)(Some(&deps), this.deps.as_ref()) {
return;
}
if let Some(de) = this.destructor.take() {
de.tear_down();
}
let new_destructor = runner(&deps);
this.deps = Some(deps);
this.destructor = Some(new_destructor);
}
}
}
impl<T, F, D> Drop for UseEffectBase<T, F, D>
where
F: FnOnce(&T) -> D + 'static,
T: 'static,
D: TearDown,
{
fn drop(&mut self) {
if let Some(destructor) = self.destructor.take() {
destructor.tear_down()
}
}
}
fn use_effect_base<T, D>(
runner: impl FnOnce(&T) -> D + 'static,
deps: T,
effect_changed_fn: fn(Option<&T>, Option<&T>) -> bool,
) -> impl Hook<Output = ()>
where
T: 'static,
D: TearDown,
{
struct HookProvider<T, F, D>
where
F: FnOnce(&T) -> D + 'static,
T: 'static,
D: TearDown,
{
runner: F,
deps: T,
effect_changed_fn: fn(Option<&T>, Option<&T>) -> bool,
}
impl<T, F, D> Hook for HookProvider<T, F, D>
where
F: FnOnce(&T) -> D + 'static,
T: 'static,
D: TearDown,
{
type Output = ();
fn run(self, ctx: &mut HookContext) -> Self::Output {
let Self {
runner,
deps,
effect_changed_fn,
} = self;
let state = ctx.next_effect(|_| -> RefCell<UseEffectBase<T, F, D>> {
RefCell::new(UseEffectBase {
runner_with_deps: None,
destructor: None,
deps: None,
effect_changed_fn,
})
});
state.borrow_mut().runner_with_deps = Some((deps, runner));
}
}
HookProvider {
runner,
deps,
effect_changed_fn,
}
}
/// `use_effect` is used for hooking into the component's lifecycle and creating side effects.
///
/// The callback is called every time after the component's render has finished.
///
/// # Example
///
/// ```rust
/// use yew::prelude::*;
/// # use std::rc::Rc;
///
/// #[function_component(UseEffect)]
/// fn effect() -> Html {
/// let counter = use_state(|| 0);
///
/// let counter_one = counter.clone();
/// use_effect(move || {
/// // Make a call to DOM API after component is rendered
/// gloo::utils::document().set_title(&format!("You clicked {} times", *counter_one));
///
/// // Perform the cleanup
/// || gloo::utils::document().set_title(&format!("You clicked 0 times"))
/// });
///
/// let onclick = {
/// let counter = counter.clone();
/// Callback::from(move |_| counter.set(*counter + 1))
/// };
///
/// html! {
/// <button {onclick}>{ format!("Increment to {}", *counter) }</button>
/// }
/// }
/// ```
///
/// # Destructor
///
/// Any type implementing [`TearDown`] can be used as destructor, which is called when the component
/// is re-rendered
///
/// ## Tip
///
/// The callback can return [`()`] if there is no destructor to run.
#[hook]
pub fn use_effect<F, D>(f: F)
where
F: FnOnce() -> D + 'static,
D: TearDown,
{
use_effect_base(|_| f(), (), |_, _| true);
}
/// This hook is similar to [`use_effect`] but it accepts dependencies.
///
/// Whenever the dependencies are changed, the effect callback is called again.
/// To detect changes, dependencies must implement [`PartialEq`].
///
/// # Note
/// The destructor also runs when dependencies change.
///
/// # Example
///
/// ```rust
/// use yew::{function_component, html, use_effect_with, Html, Properties};
/// # use gloo::console::log;
///
/// #[derive(Properties, PartialEq)]
/// pub struct Props {
/// pub is_loading: bool,
/// }
///
/// #[function_component]
/// fn HelloWorld(props: &Props) -> Html {
/// let is_loading = props.is_loading.clone();
///
/// use_effect_with(is_loading, move |_| {
/// log!(" Is loading prop changed!");
/// });
///
/// html! {
/// <>{"Am I loading? - "}{is_loading}</>
/// }
/// }
/// ```
///
/// # Tips
///
/// ## Only on first render
///
/// Provide a empty tuple `()` as dependencies when you need to do something only on the first
/// render of a component.
///
/// ```rust
/// use yew::{function_component, html, use_effect_with, Html};
/// # use gloo::console::log;
///
/// #[function_component]
/// fn HelloWorld() -> Html {
/// use_effect_with((), move |_| {
/// log!("I got rendered, yay!");
/// });
///
/// html! { "Hello" }
/// }
/// ```
///
/// ## On destructing or last render
///
/// Use [Only on first render](#only-on-first-render) but put the code in the cleanup function.
/// It will only get called when the component is removed from view / gets destroyed.
///
/// ```rust
/// use yew::{function_component, html, use_effect_with, Html};
/// # use gloo::console::log;
///
/// #[function_component]
/// fn HelloWorld() -> Html {
/// use_effect_with((), move |_| {
/// || {
/// log!("Noo dont kill me, ahhh!");
/// }
/// });
///
/// html! { "Hello" }
/// }
/// ```
///
/// Any type implementing [`TearDown`] can be used as destructor
///
/// ### Tip
///
/// The callback can return [`()`] if there is no destructor to run.
pub fn use_effect_with<T, F, D>(deps: T, f: F) -> impl Hook<Output = ()>
where
T: PartialEq + 'static,
F: FnOnce(&T) -> D + 'static,
D: TearDown,
{
use_effect_base(f, deps, |lhs, rhs| lhs != rhs)
}