Pre-defined Hooks

use_state

use_state is used to manage state in a function component. It returns a UseStateHandle object which Derefs to the current value and provides a set method to update the value.

The hook takes a function as input which determines the initial state. This value remains up-to-date on subsequent renders.

The setter function is guaranteed to be the same across the entire component lifecycle. You can safely omit the UseStateHandle from the dependents of use_effect_with_deps if you only intend to set values from within the hook.

This hook will always trigger a re-render upon receiving a new state. See use_state_eq if you want the component to only re-render when the state changes.

Example

  1. use yew::{Callback, function_component, html, use_state};
  2. #[function_component(UseState)]
  3. fn state() -> Html {
  4. let counter = use_state(|| 0);
  5. let onclick = {
  6. let counter = counter.clone();
  7. Callback::from(move |_| counter.set(*counter + 1))
  8. };
  9. html! {
  10. <div>
  11. <button {onclick}>{ "Increment value" }</button>
  12. <p>
  13. <b>{ "Current value: " }</b>
  14. { *counter }
  15. </p>
  16. </div>
  17. }
  18. }

Pre-defined Hooks - 图1caution

The value held in the handle will reflect the value at the time the handle is returned by the use_state. It is possible that the handle does not dereference to an up to date value if you are moving it into a use_effect_with_deps hook. You can register the state to the dependents so the hook can be updated when the value changes.

use_state_eq

This hook has the same effect as use_state but will only trigger a re-render when the setter receives a value that prev_state != next_state.

This hook requires the state object to implement PartialEq.

use_ref

use_ref is used for obtaining an immutable reference to a value. Its state persists across renders.

use_ref can be useful for keeping things in scope for the lifetime of the component, so long as you don’t store a clone of the resulting Rc anywhere that outlives the component.

If you need a mutable reference, consider using use_mut_ref. If you need the component to be re-rendered on state change, consider using use_state.

  1. // EventBus is an implementation of yew_agent::Agent
  2. use website_test::agents::EventBus;
  3. use yew::{function_component, html, use_ref, use_state, Callback};
  4. use yew_agent::Bridged;
  5. #[function_component(UseRef)]
  6. fn ref_hook() -> Html {
  7. let greeting = use_state(|| "No one has greeted me yet!".to_owned());
  8. {
  9. let greeting = greeting.clone();
  10. use_ref(|| EventBus::bridge(Callback::from(move |msg| {
  11. greeting.set(msg);
  12. })));
  13. }
  14. html! {
  15. <div>
  16. <span>{ (*greeting).clone() }</span>
  17. </div>
  18. }
  19. }

use_mut_ref

use_mut_ref is used for obtaining a mutable reference to a value. Its state persists across renders.

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

  1. use web_sys::HtmlInputElement;
  2. use yew::{
  3. events::Event,
  4. function_component, html, use_mut_ref, use_state,
  5. Callback, TargetCast,
  6. };
  7. #[function_component(UseMutRef)]
  8. fn mut_ref_hook() -> Html {
  9. let message = use_state(|| "".to_string());
  10. let message_count = use_mut_ref(|| 0);
  11. let onclick = Callback::from(move |_| {
  12. let window = gloo_utils::window();
  13. if *message_count.borrow_mut() > 3 {
  14. window.alert_with_message("Message limit reached").unwrap();
  15. } else {
  16. *message_count.borrow_mut() += 1;
  17. window.alert_with_message("Message sent").unwrap();
  18. }
  19. });
  20. let onchange = {
  21. let message = message.clone();
  22. Callback::from(move |e: Event| {
  23. let input: HtmlInputElement = e.target_unchecked_into();
  24. message.set(input.value());
  25. })
  26. };
  27. html! {
  28. <div>
  29. <input {onchange} value={(*message).clone()} />
  30. <button {onclick}>{ "Send" }</button>
  31. </div>
  32. }
  33. }

use_node_ref

use_node_ref is used for obtaining a NodeRef that persists across renders.

When conditionally rendering elements you can use NodeRef in conjunction with use_effect_with_deps to perform actions each time an element is rendered and just before its going to be removed from the DOM.

Example

  1. use web_sys::HtmlInputElement;
  2. use yew::{
  3. function_component, functional::*, html,
  4. NodeRef
  5. };
  6. #[function_component(UseRef)]
  7. pub fn ref_hook() -> Html {
  8. let input_ref = use_node_ref();
  9. let value = use_state(|| 25f64);
  10. let onclick = {
  11. let input_ref = input_ref.clone();
  12. let value = value.clone();
  13. move |_| {
  14. if let Some(input) = input_ref.cast::<HtmlInputElement>() {
  15. value.set(*value + input.value_as_number());
  16. }
  17. }
  18. };
  19. html! {
  20. <div>
  21. <input ref={input_ref} type="number" />
  22. <button {onclick}>{ format!("Add input to {}", *value) }</button>
  23. </div>
  24. }
  25. }

use_reducer

use_reducer is an alternative to use_state. It is used to handle component’s state and is used when complex actions needs to be performed on said state.

It accepts an initial state function and returns a UseReducerHandle that dereferences to the state, and a dispatch function. The dispatch function takes one argument of type Action. When called, the action and current value are passed to the reducer function which computes a new state which is returned, and the component is re-rendered.

The dispatch function is guaranteed to be the same across the entire component lifecycle. You can safely omit the UseReducerHandle from the dependents of use_effect_with_deps if you only intend to dispatch values from within the hooks.

The state object returned by the initial state function is required to implement a Reducible trait which provides an Action type and a reducer function.

This hook will always trigger a re-render upon receiving an action. See use_reducer_eq if you want the component to only re-render when the state changes.

Example

  1. use yew::prelude::*;
  2. use std::rc::Rc;
  3. /// reducer's Action
  4. enum CounterAction {
  5. Double,
  6. Square,
  7. }
  8. /// reducer's State
  9. struct CounterState {
  10. counter: i32,
  11. }
  12. impl Default for CounterState {
  13. fn default() -> Self {
  14. Self { counter: 1 }
  15. }
  16. }
  17. impl Reducible for CounterState {
  18. /// Reducer Action Type
  19. type Action = CounterAction;
  20. /// Reducer Function
  21. fn reduce(self: Rc<Self>, action: Self::Action) -> Rc<Self> {
  22. let next_ctr = match action {
  23. CounterAction::Double => self.counter * 2,
  24. CounterAction::Square => self.counter.pow(2)
  25. };
  26. Self { counter: next_ctr }.into()
  27. }
  28. }
  29. #[function_component(UseReducer)]
  30. fn reducer() -> Html {
  31. // The use_reducer hook takes an initialization function which will be called only once.
  32. let counter = use_reducer(CounterState::default);
  33. let double_onclick = {
  34. let counter = counter.clone();
  35. Callback::from(move |_| counter.dispatch(CounterAction::Double))
  36. };
  37. let square_onclick = {
  38. let counter = counter.clone();
  39. Callback::from(move |_| counter.dispatch(CounterAction::Square))
  40. };
  41. html! {
  42. <>
  43. <div id="result">{ counter.counter }</div>
  44. <button onclick={double_onclick}>{ "Double" }</button>
  45. <button onclick={square_onclick}>{ "Square" }</button>
  46. </>
  47. }
  48. }

Pre-defined Hooks - 图2caution

The value held in the handle will reflect the value of at the time the handle is returned by the use_reducer. It is possible that the handle does not dereference to an up to date value if you are moving it into a use_effect_with_deps hook. You can register the state to the dependents so the hook can be updated when the value changes.

use_reducer_eq

This hook has the same effect as use_reducer but will only trigger a re-render when the reducer function produces a value that prev_state != next_state.

This hook requires the state object to implement PartialEq in addition to the Reducible trait required by use_reducer.

use_effect

use_effect is used for hooking into the component’s lifecycle. Similar to rendered from the Component trait, use_effect takes a function which is called after the render finishes.

The input function has to return a closure, the destructor, which is called when the component is destroyed. The destructor can be used to clean up the effects introduced and it can take ownership of values to delay dropping them until the component is destroyed.

Example

  1. use yew::{Callback, function_component, html, use_effect, use_state};
  2. #[function_component(UseEffect)]
  3. fn effect() -> Html {
  4. let counter = use_state(|| 0);
  5. {
  6. let counter = counter.clone();
  7. use_effect(move || {
  8. // Make a call to DOM API after component is rendered
  9. gloo_utils::document().set_title(&format!("You clicked {} times", *counter));
  10. // Perform the cleanup
  11. || gloo_utils::document().set_title("You clicked 0 times")
  12. });
  13. }
  14. let onclick = {
  15. let counter = counter.clone();
  16. Callback::from(move |_| counter.set(*counter + 1))
  17. };
  18. html! {
  19. <button {onclick}>{ format!("Increment to {}", *counter) }</button>
  20. }
  21. }

use_effect_with_deps

Sometimes, it’s needed to manually define dependencies for use_effect. In such cases, we use use_effect_with_deps.

  1. use yew::use_effect_with_deps;
  2. use_effect_with_deps(
  3. move |_| {
  4. // ...
  5. || ()
  6. },
  7. (), // dependents
  8. );

Note: dependents must implement PartialEq.

use_context

use_context is used for consuming contexts in function components.

Example

  1. use yew::{ContextProvider, function_component, html, use_context, use_state};
  2. /// App theme
  3. #[derive(Clone, Debug, PartialEq)]
  4. struct Theme {
  5. foreground: String,
  6. background: String,
  7. }
  8. /// Main component
  9. #[function_component(App)]
  10. pub fn app() -> Html {
  11. let ctx = use_state(|| Theme {
  12. foreground: "#000000".to_owned(),
  13. background: "#eeeeee".to_owned(),
  14. });
  15. html! {
  16. // `ctx` is type `Rc<UseStateHandle<Theme>>` while we need `Theme`
  17. // so we deref it.
  18. // It derefs to `&Theme`, hence the clone
  19. <ContextProvider<Theme> context={(*ctx).clone()}>
  20. // Every child here and their children will have access to this context.
  21. <Toolbar />
  22. </ContextProvider<Theme>>
  23. }
  24. }
  25. /// The toolbar.
  26. /// This component has access to the context
  27. #[function_component(Toolbar)]
  28. pub fn toolbar() -> Html {
  29. html! {
  30. <div>
  31. <ThemedButton />
  32. </div>
  33. }
  34. }
  35. /// Button placed in `Toolbar`.
  36. /// As this component is a child of `ThemeContextProvider` in the component tree, it also has access to the context.
  37. #[function_component(ThemedButton)]
  38. pub fn themed_button() -> Html {
  39. let theme = use_context::<Theme>().expect("no ctx found");
  40. html! {
  41. <button style={format!("background: {}; color: {};", theme.background, theme.foreground)}>
  42. { "Click me!" }
  43. </button>
  44. }
  45. }