useTheme
Read the current theme from ThemeProvider context, with companion hooks for loading state and dark-mode detection.
useTheme returns the current theme from ThemeProvider. If you pass a theme, the hook returns that theme instead. The companion hooks useThemeIsLoading, useThemeStatus, and useIsDarkTheme report the loading state and whether the theme is dark. See Apply theming for setting up ThemeProvider.
Basic usage
import type { ITheme } from "@gooddata/sdk-model";
import { useTheme } from "@gooddata/sdk-ui-theme-provider";
function MyComponent({ theme: themeProp }: { theme?: ITheme }) {
// Uses themeProp if defined, otherwise falls back to the context value
const theme = useTheme(themeProp);
const primaryColor = theme?.palette?.primary?.base ?? "#14b2a9";
return <div style={{ color: primaryColor }}>Themed content</div>;
}
Wait for the theme to load
useThemeIsLoading tells you whether ThemeProvider is still loading the theme from the backend:
import { useTheme, useThemeIsLoading } from "@gooddata/sdk-ui-theme-provider";
function MyComponent() {
const theme = useTheme();
const isLoading = useThemeIsLoading();
if (isLoading) {
return <div>Loading theme...</div>;
}
return <div style={{ color: theme?.palette?.primary?.base }}>Ready</div>;
}
Detect a dark theme
useIsDarkTheme tells you whether the current theme is dark:
import { useIsDarkTheme } from "@gooddata/sdk-ui-theme-provider";
function MyComponent() {
const isDark = useIsDarkTheme();
return <div className={isDark ? "dark-mode" : "light-mode"}>Content</div>;
}
Parameters
| Parameter | Type | Description |
|---|---|---|
theme | ITheme | undefined | Optional theme override for useTheme. If defined, the hook returns it instead of the context value. |
useThemeIsLoading, useThemeStatus, and useIsDarkTheme take no parameters.
Return value
useTheme:ITheme | undefineduseThemeIsLoading:boolean | undefineduseThemeStatus:"pending" | "loading" | "success" | undefineduseIsDarkTheme:boolean
Notes
- Without a
ThemeProviderup the tree,useThemereturnsundefined, so guard palette lookups with optional chaining or a fallback value. useThemeStatustells apart"pending"(no load started),"loading"(the theme is being fetched), and"success"(the theme is resolved). Use it whenuseThemeIsLoadingisn’t precise enough.useIsDarkThemereturnsfalsewhen there is no theme, so it’s safe to call outsideThemeProvider.
Related
Apply custom themes to GoodData.UI dashboards and visualizations by wrapping your app in ThemeProvider.
Retrieve the analytical backend from BackendProvider context, with an optional prop override or strict variant.
Read the workspace identifier from WorkspaceProvider context, with an optional override and a strict variant that throws when unset.
Configure chart appearance, axes, legends, colors, and data labels.