Performance: Variables, or Binding? #82
-
I have a curious question. My goal is to reduce the amount of hook calls and receive the best performance. My idea is to bind 2 variables, Which is faster - Binding the colors directly or using variables and letting the browser re-render on variable changes? Variable approach: fn variables() -> StyleSource<'static> {
let theme = use_theme();
css!(
r#"
:root {
--bg: ${bg},
--fg: ${fg},
}
"#,
bg = theme.bg1.to_css(),
fg = thene.fg1.to_css(),
)
}
#[function_component(Root)]
pub fn root() -> Html {
html! {
<ThemeProvider>
<Global css={ variables() } />
<ThemeSwitcher />
</ThemeProvider>
<App />
}
}
#[function_component(ThemeSwitcher)]
pub fn theme_switcher() -> Html {
let theme = use_theme();
let other_theme = match theme.kind() {
ThemeChoice::Light => ThemeChoice::Dark,
ThemeChoice::Dark => ThemeChoice::Light,
};
let switch_theme = Callback::from(move |_| theme.set(other_theme));
html! {
<button onclick={ switch_theme }>
{ "switch" }
</button>
}
}
#[function_component(App)]
fn app() -> Html {
html! {
<>
<h2 class={css!("color: var(--fg)")}>
{ "Hello!" }
</h2>
</>
}
} Binding colors directly: fn variables() -> StyleSource<'static> {
let theme = use_theme();
css!(
r#"
:root {
bakcground-color: ${bg},
color: ${fg},
}
"#,
bg = theme.bg1.to_css(),
fg = thene.fg1.to_css(),
)
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
I believe letting the browser handle the vars and rebinding thereof is slightly faster:
That being said, it can be more ergonomic to let each component build its style dynamically instead of setting a ton of variables at the top level. For a small number of colors though, e.g. |
Beta Was this translation helpful? Give feedback.
I believe letting the browser handle the vars and rebinding thereof is slightly faster:
That being said, it can be more ergonomic to let each component build its style dynamically instead of setting a ton of variables at the top level. For a small number of colors though, e.g.
--dark-primary
,--darker-primary
,--primary
or what have you, variables still work, but when you also includes things like margin sizes, shadows, grid sizes and all the other things, v…