Chakra UI v2: Unresolved fallback strategy when localStorage and sessionStorage are blocked
0 reputation · 06 Apr 2021, 08:12 UTC
0 reputation · 06 Apr 2021, 08:12 UTC
We want to understand how Chakra UI’s color‑mode hook behaves when both primary and secondary storage mechanisms are unavailable, such as in strict privacy or incognito modes.
The library uses localStorage by default, with an optional sessionStorage fallback introduced in v2. Neither storage is guaranteed to be accessible. The documentation does not specify what happens when both are blocked.
Should the hook revert to the system preference, silently fallback to a default mode, or throw an error? The current implementation appears to default to the system preference but this is not explicitly documented.
When localStorage and sessionStorage are both blocked, Chakra UI v2's useColorMode hook falls back to the system preference detected via matchMedia('(prefers-color-scheme: dark)'). This behavior is implemented through silent try-catch blocks around storage access without throwing errors.
localStorage.getItem('chakra-ui-color-mode')sessionStorage.getItem('chakra-ui-color-mode')window.matchMedia('(prefers-color-scheme: dark)') to determine initial color modeChakra UI v2 does not provide a built-in configuration option to override this default fallback behavior. The config prop in ChakraProvider only supports cssVariablePrefix and cssLayerNames settings, but no storage or fallback customization.
Falling back to system preference on every reload can cause unexpected UX changes when users switch between light and dark modes at the OS level. Since the color mode is not persisted, users may experience mode changes they did not explicitly request.
localStorage and sessionStorage in browser devtools Application tabwindow.matchMedia('(prefers-color-scheme: dark)') value to confirm detection@chakra-ui/hooks package for exact try-catch implementationIf the default fallback behavior is undesirable, consider:
storageManager prop in ChakraProvider (available in v2.8+) to provide custom storage implementationUse comments to ask for clarification. Post a solution as an answer.
33,775 reputation · 06 Apr 2021, 14:23 UTC
While the default fallback sequence is hardcoded, it is important to note that Chakra UI v2 allows for a complete override of the storage logic. If the system preference fallback is insufficient for your UX requirements, you can provide a custom colorModeManager object to the ChakraProvider.
By implementing your own get and set methods, you can bypass the standard localStorage/sessionStorage chain entirely. This is particularly useful for:
Verification: Pass an object like { get: () => 'dark', set: () => {} } to the provider to confirm the hook ignores both storage and system preferences.