Chakra UI (v2) - ColorModeProvider and ColorModeScript
Posted on Jul 22, 2023 in Blog Posts
At the time of writing, @chakra-ui/react
's version is 2.8.0
.
Overview
This post explores the functionality differences between Chakra UI's ColorModeProvider
and ColorModeScript
. I originally wrote this as an answer on Stack Overflow on July 22, 2023.
ColorModeProvider
ColorModeProvider
provides functionality for toggling and rendering components by color mode, like toggling component CSS classes from light to dark. Changing toggleColorMode
for content not wrapped in/using the ColorModeProvider
would not result in changing the content's color scheme.
Luckily, ColorModeProvider
is built into ChakraProvider
and ChakraBaseProvider
1,2 with newer versions, and does not need to be added separately.3
ChakraProvider
/ChakraBaseProvider
return includes ColorModeProvider
2:
ColorModeScript
ColorModeScript
generates and inserts a script as the first item in the root element that helps read the user's system preference for color mode, as well as set and get the user's color preference setting from local storage. It also adds/removes the appropriate body CSS class for Chakra's light/dark mode.4 The ColorModeScript
configuration is placed as close as possible to the start of the body
tag.
The documentation for ColorModeScript
is quite short, so I looked at the source code5 and sandbox tested6 to understand its impact. The documentation mentions that preference storage can also be handled server-side, and if implemented server-side, the ColorModeScript
does not need to be used.7
Footnotes
The Chakra UI contributors significantly restructured the repository in preparation for v3 and the files are no longer in the same location as when this was written. The GitHub links below point to a blob committed around July 18, 2023.
ChakraProvider
/ChakraBaseProvider
source code where it returns ThemeProvider
and ColorModeProvider
wrapping children ChakraProvider
over ThemeProvider
/ColorModeProvider
pattern