Wraps system dark mode in a React hook. Make dark mode integration as simple as it should be!
useDarkMode
is the only exported function of this package and this is how you use it:
import { useDarkMode } from "@a1knla/react-dark-mode"
export default function MyComponent() {
const isDarkMode = useDarkMode()
return (
<>
Current mode: {isDarkMode ? "dark" : "light"}. Try changing your system
settings and this will update automatically.
</>
)
}
MUI and JoyUI have their own dark mode systems. Now you can sync them with the system dark mode:
import { useColorScheme } from "@mui/joy"
import { useDarkMode } from "@a1knla/react-dark-mode"
function syncMuiWithSystemDarkMode() {
const isDarkMode = useDarkMode()
const { setMode } = useColorScheme()
useEffect(() => {
setMode(isDarkMode ? "dark" : "light")
}, [isDarkMode, setMode])
}
function App() {
syncMuiJoyUiWithSystemDarkMode()
// Your app code...
}
Good code documents itself:
export type DarkModeProps = {
/**
* Whether to detect system dark mode. Defaults to `true`.
*/
detectSystemDarkMode?: boolean
/**
* Whether to automatically set dark mode according to local time. Defaults to `false`, and 18:00 - 6:00 is considered as night time.
*/
detectTimeBasedDarkMode?: boolean
/**
* The interval to detect time based dark mode. Defaults to `1000`.
*/
timeDetectionIntervalMillis?: number
/**
* Custom predicate to determine whether it's night time.
*/
customNightTimePredicate?: () => boolean
}
export function useDarkMode(props?: DarkModeProps): boolean