1.0.10 • Published 1 year ago

@anatoliygatt/use-prefers-color-scheme v1.0.10

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

🚀 Getting Started

🐇 Jump Start

npm install @anatoliygatt/use-prefers-color-scheme
import { usePrefersColorScheme } from '@anatoliygatt/use-prefers-color-scheme';

function Example() {
  const preferredColorScheme = usePrefersColorScheme();
  const isDarkColorSchemePreferred = preferredColorScheme === 'dark';
  return (
    <div>
      Preferred Color Scheme:{' '}
      {isDarkColorSchemePreferred ? '🌚 Dark' : '🌞 Light'}
    </div>
  );
}

💻 Live Demo

Open in CodeSandbox

⚙️ Usage with Server Side Rendering (SSR)

Frameworks like Next.js and Gatsby take advantage of server-side rendering, which means that the HTML is pre-rendered at some point before it's sent to the browser. When we first render our React component tree, we don't know whether the user prefers light or dark color scheme.

It may lead to the markup mismatches during hydration. In order to prevent this, we need to set the ssr option provided by the usePrefersColorScheme() hook to true, like so:

usePrefersColorScheme({ ssr: true });

This will guarantee no markup mismatches between the original server render and the first client render, however, we will have to make a compromise: force a dark color scheme for all users in the very first render.

👨🏼‍⚖️ License

MIT

1.0.10

1 year ago

1.0.9

1 year ago

1.0.8

1 year ago

1.0.7

1 year ago

1.0.6

1 year ago

1.0.5

2 years ago

1.0.4

2 years ago

1.0.3

2 years ago

1.0.2

2 years ago

1.0.1

2 years ago

1.0.0

2 years ago