Skip to content

Chakra UI (v2) - ColorModeProvider and ColorModeScript

Posted on Jul 22, 2023 in Blog Posts

Version Reference

At the time of writing, @chakra-ui/react's version is 2.8.0.


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 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 ChakraBaseProvider1,2 with newer versions, and does not need to be added separately.3

ChakraProvider/ChakraBaseProvider return includes ColorModeProvider2:

return (
<ThemeProvider theme={theme as Dict} cssVarsRoot={cssVarsRoot}>
{/* Children/additional settings omitted to save lines */}


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



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.

1. chakra-ui GitHub : Source code for ChakraProvider
2. See link 1 line 100. Shows ChakraProvider/ChakraBaseProvider source code where it returns ThemeProvider and ColorModeProvider wrapping children
3. chakra-ui GitHub : Patch notes v1.6.0 shows it's recommended to use ChakraProvider over ThemeProvider/ColorModeProvider pattern
4. chakra-ui GitHub : Shows the script set in the root element (example also above) that manages local storage preference, body class names, etc. See line 34 re: localStorage.
5. See link 4 for ColorModeScript source code
6. Replit Sandbox : Credit to user tresorama for the helpful sandbox
7. chakra-ui GitHub : v2.0.1 patch notes indicate addition of server-side setting with configuration examples, around line 213 at time of writing.