Color Mode allows users to switch your app's color mode between light and dark modes, providing a pleasant user experience.
Install next-themes in your project
pnpm install next-themes
Import and wrap your app with the ThemeProvider
component
import { ThemeProvider } from 'next-themes'
const App = ({ children }) => {
return (
<ThemeProvider attribute="class" disableTransitionOnChange>
{children}
</ThemeProvider>
)
}
Use useTheme
to access theme state and create a toggle button
import { useTheme } from 'next-themes'
const ColorModeToggle = () => {
const { theme, setTheme } = useTheme()
const toggleTheme = () => {
setTheme(theme === 'light' ? 'dark' : 'light')
}
return <button onClick={toggleTheme}>{theme}</button>
}