Pure Components

A function component is considered pure when the returned Html is deterministically derived from its props, and its view function mutates no state or has other side-effects.

For example below is a pure component. For a given prop is_loading it will always result in the same Html without any side effects.

  1. use yew::{Properties, function_component, Html, html};
  2. #[derive(Properties, PartialEq)]
  3. pub struct Props {
  4. pub is_loading: bool,
  5. }
  6. #[function_component]
  7. fn HelloWorld(props: &Props) -> Html {
  8. if props.is_loading {
  9. html! { "Loading" }
  10. } else {
  11. html! { "Hello world" }
  12. }
  13. }

Pure Components - 图1备注

If you have an internal pure component that makes no use of hooks and other component machinery, you can often write it instead as a normal function returning Html and avoid a bit of overhead for Yew, related to running the component lifecycle. Use expression syntax to render them in html!.

Impure components

You might wonder if a component can be impure if it does not use any globals, since its just a function that is called every render. This is where the next topic comes in - hooks