useTheme
Read the current theme as typed values
useTheme reads the current theme as a typed object whose values update with
the surrounding theme context.
Tamagui themes operate much like CSS variables, so they can nest and override each other contextually.
The returned object proxies up through every parent theme to your tokens, just like CSS variables at runtime.
Example:
The useTheme hook returns your Theme turned into a ThemeParsed, which means
it turns all values into a Variable:
The useTheme hook adds a .get() helper function on each Variable for
performance. On web, .get() returns the .variable property and avoids
re-rendering on value changes, because CSS custom properties handle updates
directly in the browser. On native, .get() returns .val and re-renders on
change. When the fastSchemeChange setting
is enabled, get() returns a DynamicColorIOS
value on iOS to avoid re-renders there as well. Passing get('web') restricts
that optimization to web.
You can mix and match useMedia and useTheme, and the compiler understands
most basic usages, even with nested logic or constants within the file or
imports whitelisted in your build setup:
This will compile on the web to:
And the following CSS:
Using outside of styling
You can useTheme() (and useMedia()) at runtime. Like useMedia, useTheme will
only re-render when it has to, and often you can skip re-renders altogether by
either passing the values to a Tamagui styled component, or by using the helper
getVariable:
getVariable
If you access theme.bg.val in your render function, the component will only
re-render when theme.bg changes.
Reading another theme
useTheme takes no arguments and reads the ambient theme. To read values under
a different theme, wrap the reader in <Theme name="..."> and call useTheme
inside it.