Overview
TheuseTheme hook provides access to the current theme and a function to update it. The theme is persisted to localStorage and automatically applied to the document root element.
Import
Type Signature
Return Value
The current active theme. Defaults to
'dark' if no theme is stored in localStorage.Function to update the theme. Accepts either
'white' or 'dark' as the new theme value.When called, this function:- Updates the theme state
- Persists the new theme to localStorage
- Sets the
data-themeattribute on the document root element
Usage Example
Basic Theme Toggle
Theme Selector Component
Conditional Rendering Based on Theme
Setup Required
TheuseTheme hook must be used within a ThemeProvider. Wrap your application root with the provider:
How It Works
-
Initialization: On mount, the provider checks localStorage for a saved theme preference. If none exists, defaults to
'dark' -
Persistence: When
setThemeis called:- The new theme value is saved to localStorage under the key
"theme" - The
data-themeattribute is set ondocument.documentElement - The state updates, triggering a re-render
- The new theme value is saved to localStorage under the key
-
CSS Integration: The theme is applied via the
data-themeattribute, allowing CSS to respond:
Error Handling
IfuseTheme is called outside of a ThemeProvider, it throws an error:
Storage Key
The theme preference is stored in localStorage with the key:"theme"
Source
Implemented in:src/app/providers/Theme.tsx:25