diff --git a/examples/use_ref.rs b/examples/use_ref.rs new file mode 100644 index 000000000..358b9c266 --- /dev/null +++ b/examples/use_ref.rs @@ -0,0 +1,21 @@ +use std::collections::HashMap; + +use dioxus::prelude::*; +fn main() {} + +fn app(cx: Scope) -> Element { + let val = use_ref(&cx, || HashMap::::new()); + + // Pull the value out locally + let p = val.read(); + + // to get an &HashMap we have to "reborrow" through the RefCell + // Be careful: passing this into children might cause a double borrow of the RefCell and a panic + let g = &*p; + + cx.render(rsx! { + div { + "hi" + } + }) +} diff --git a/packages/hooks/src/useref.rs b/packages/hooks/src/useref.rs index 3ddf86e8c..a0b9189d0 100644 --- a/packages/hooks/src/useref.rs +++ b/packages/hooks/src/useref.rs @@ -42,6 +42,17 @@ impl UseRef { self.value.borrow_mut() } + /// Take a reference to the inner value termporarily and produce a new value + pub fn with(&self, f: impl FnOnce(&T) -> O) -> O { + f(&*self.read()) + } + + /// Take a reference to the inner value termporarily and produce a new value, + /// modifying the original in place. + pub fn with_mut(&self, f: impl FnOnce(&mut T) -> O) -> O { + f(&mut *self.write()) + } + pub fn needs_update(&self) { (self.update_callback)(); }