mirror of https://github.com/yewstack/yew
35 lines
928 B
Plaintext
35 lines
928 B
Plaintext
---
|
|
title: "use_memo"
|
|
---
|
|
|
|
`use_memo` is used for obtaining an immutable reference to a memoized value.
|
|
Its state persists across renders.
|
|
Its value will be recalculated only if any of the dependencies values change.
|
|
|
|
`use_memo` 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.
|
|
|
|
```rust
|
|
use yew::{function_component, html, use_memo, use_state, Callback, Html, Properties};
|
|
|
|
#[derive(PartialEq, Properties)]
|
|
pub struct Props {
|
|
pub step: usize,
|
|
}
|
|
|
|
#[function_component(UseMemo)]
|
|
fn ref_hook(props: &Props) -> Html {
|
|
// Will only get recalculated if `props.step` value changes
|
|
let message = use_memo(
|
|
|step| format!("{}. Do Some Expensive Calculation", step),
|
|
props.step
|
|
);
|
|
|
|
html! {
|
|
<div>
|
|
<span>{ (*message).clone() }</span>
|
|
</div>
|
|
}
|
|
}
|
|
```
|