@madebysid/usetheme

Simple-to-use React hook to add light/dark modes to your React app.

Usage no npm install needed!

<script type="module">
  import madebysidUsetheme from 'https://cdn.skypack.dev/@madebysid/usetheme';
</script>

README

useTheme

Simple-to-use React hook to add light/dark modes to your React app.

✅️ Respects user OS preference
✅️️ Respects manual theme overrides
✅️ Snaps back to OS preference if needed
✅️ Syncs theme across tabs and windows

Installation

npm i @madebysid/usetheme

--OR--

yarn add @madebysid/usetheme

Usage

  1. Wrap your app in a ThemeProvider:
import { ThemeProvider } from "useTheme";

ReactDOM.render(
  <React.StrictMode>
    <ThemeProvider>{/* ... Rest of your app */}</ThemeProvider>
  </React.StrictMode>,
  document.getElementById("root")
);
  1. Use the useTheme hook whenever you need access to the theme:
import { useTheme } from "useTheme";

function Component() {
  const { theme, setTheme } = useTheme();

  return (
    <>
      Current theme: {theme}
      <button onClick={setTheme("dark")}>🌚</button>
      <button onClick={setTheme("light")}>🌝</button>
    </>
  );
}