mirror of
https://github.com/yewstack/yew.git
synced 2025-12-08 21:26:25 +00:00
I was originally going to put a PR to fix "has not side-effects", but I also re-read this sentence and realized it could be interpreted as saying a pure function returns its parameters, not a deterministic value based on its parameters.
37 lines
1.0 KiB
Plaintext
37 lines
1.0 KiB
Plaintext
---
|
|
title: "Pure Components"
|
|
---
|
|
|
|
## Pure function definition
|
|
|
|
A function is considered pure when the return values are deterministic given the same parameters, and it has no side-effects.
|
|
|
|
## Pure components
|
|
|
|
In the same sense component is pure when it does not have any state or side_effects and with the given props always returns the same `Html`.
|
|
|
|
For example below is a pure component, for a given prop `is_loading` it will always result in same `Html` without any side effects.
|
|
|
|
```rust
|
|
use yew::{Properties, function_component, Html, html};
|
|
|
|
#[derive(Properties, PartialEq)]
|
|
pub struct Props {
|
|
pub is_loading: bool,
|
|
}
|
|
|
|
#[function_component]
|
|
fn HelloWorld(props: &Props) -> Html {
|
|
if props.is_loading.clone() {
|
|
html! { "Loading" }
|
|
} else {
|
|
html! { "Hello world" }
|
|
}
|
|
}
|
|
```
|
|
|
|
## Un-pure components
|
|
|
|
Though you probably wonder how can a component even be un-pure if its just a function that is called every render and if it does not use any globals.
|
|
This is where the next topic comes in - [hooks](./hooks)
|