React hook for retrieving the current browser theme and listening for changes.
This is a React Hook that accepts a callback function provided to it every time the theme changes.
The theme of the browser is returned as light
or dark
, light
being the default if there is no explicit theme setting by the user.
yarn add react-use-browser-theme
or
npm install --save react-use-browser-theme
import React, { useState, useCallback, useLayoutEffect } from 'react'
import { useBrowserThemeChangeListener } from 'react-use-browser-theme'
const App = () => {
const [theme, setTheme] = useState('light')
useLayoutEffect(() => {
if (matchMedia('(prefers-color-scheme: dark)').matches) {
setTheme('dark')
}
}, [])
const browserThemeListener = useCallback(
(e) => setTheme(e.matches ? 'dark' : 'light'),
[]
)
useBrowserThemeChangeListener(browserThemeListener)
return (
<div
style={{
minHeight: '100vh',
minWidth: '100vw',
color: `${theme === 'dark' ? 'white' : 'black'}`,
backgroundColor: `${theme === 'dark' ? 'black' : 'white'}`,
}}
>
Current browser theme: {theme}
</div>
)
}
export default App
MIT © emzoumpo