This is unreleased documentation for Yew Next version.
For up-to-date documentation, see the latest version on docs.rs.
yew::functional

Function use_ref

source
pub fn use_ref<T: 'static, F>(init_fn: F) -> impl Hook<Output = Rc<T>>
where F: FnOnce() -> T,
Expand description

This hook is used for obtaining a reference to a stateful value. Its state persists across renders.

Mutation must be done via interior mutability, such as Cell or RefCell.

It is important to note that you do not get notified of state changes. If you need the component to be re-rendered on state change, consider using use_state.

ยงExample

use std::cell::Cell;
use std::ops::{Deref, DerefMut};
use std::rc::Rc;

use web_sys::HtmlInputElement;
use yew::prelude::*;

#[function_component(UseRef)]
fn ref_hook() -> Html {
    let message = use_state(|| "".to_string());
    let message_count = use_ref(|| Cell::new(0));

    let onclick = Callback::from(move |e| {
        let window = gloo::utils::window();

        if message_count.get() > 3 {
            window.alert_with_message("Message limit reached");
        } else {
            message_count.set(message_count.get() + 1);
            window.alert_with_message("Message sent");
        }
    });

    let onchange = {
        let message = message.clone();
        Callback::from(move |e: Event| {
            let input: HtmlInputElement = e.target_unchecked_into();
            message.set(input.value())
        })
    };

    html! {
        <div>
            <input {onchange} value={(*message).clone()} />
            <button {onclick}>{ "Send" }</button>
        </div>
    }
}