Socket
Socket
Sign inDemoInstall

@anatoliygatt/use-prefers-color-scheme

Package Overview
Dependencies
3
Maintainers
1
Versions
11
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    @anatoliygatt/use-prefers-color-scheme

React hook for subscribing to user's color scheme preference.


Version published
Maintainers
1
Install size
13.0 kB
Created

Changelog

Source

1.0.10 (2023-04-27)

Bug Fixes

  • deps: bump yaml, @commitlint/load and semantic-release (ba9a49f)

Readme

Source

use-prefers-color-scheme Logo

use-prefers-color-scheme

React hook for subscribing to user's color scheme preference.


Github CI Workflow Status NPM Version License


🚀 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

Keywords

FAQs

Last updated on 27 Apr 2023

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc