Licence
MIT
Version
1.0.6
Deps
0
Size
113 kB
Vulns
0
Weekly
0
react-use-browser-theme
React hook for retrieving the current browser theme and listening for changes.
Description
This is a React Hook that will call 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.
Example
Install
yarn add react-use-browser-theme
or
npm install --save react-use-browser-theme
Usage
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
License
MIT emzoumpo