Skip to content

twstyled/use-system-theme

 
 

Repository files navigation

use-system-theme

NPM npm bundle size

CircleCI Maintainability

React Hook for System Theme (User preferred color scheme). Please use React > 16.8.0 for React Hooks support.

It detects the system theme and will update right after the users change the theme.

2019-12-25 19 43 26

Install

yarn add use-system-theme

or

npm install --save use-system-theme

Usage

import React from 'react'
import useSystemTheme from 'use-system-theme'

export default () => {
  const systemTheme = useSystemTheme()
  return <div>The System Theme is: {systemTheme}</div>
}

Browser support

As 2019 December, all major browsers on both mobile and desktop platforms support the prefers-color-scheme media query feature. For more details, please check: https://caniuse.com/#feat=prefers-color-scheme

SSR support

The useSystemTheme function has only one argument isSSR, and you must pass true for SSR app. Otherwise, your app may have bug like doesn't show dark them on dark theme devices.

declare const useSystemTheme: (isSSR?: boolean) => SystemTheme
import React from 'react'
import useSystemTheme from 'use-system-theme'

export default () => {
  const systemTheme = useSystemTheme(true)
  return <div>The System Theme is: {systemTheme}</div>
}

To support SSR (server side rendering), the initial theme will be always light (since we don't know the theme on the server side) and it would immediately become dark if the device's theme is dark. Unfortunately, we can't avoid this because of the React hydrate:

React expects that the rendered content is identical between the server and the client.

So that for all SSR app, the initial screen will be light and become dark immediately on dark theme devices. It's caused by the nature of how React SSR works.

Development

yarn start

To build the library and watch the file changes locally.

Develop with local examples

The local examples use the yalc to get live local version library.

You need to run yarn watch:yalc on the root directory during development. And use npx yalc add use-system-theme in the example directory under examples/. Then follow the README file in each example folder.

Note: the yalc will change the pcakge.json for the example project to "use-system-theme": "file:.yalc/use-system-theme". Please do NOT commit the change because it would cause CI/CD failure.

License

MIT © xcv58

Packages

No packages published

Languages

  • TypeScript 57.2%
  • JavaScript 42.8%