π A React Hook to handle the dark/light mode theme using Tailwind4 CSS and localStorage.
npm install react-tailwind4-theme



``bash`
npm install react-tailwind4-theme
React Tailwind4 Theme is a small library (or hook) designed for projects using Tailwind CSS v4 and React 18+. This hook, useHandleTheme, facilitates managing dark and light modes in your application by detecting system preferences and persistently storing the userβs choice. π¨
- System Theme Detection:
Checks the userβs preference using window.matchMedia("(prefers-color-scheme: dark)"). π
- Theme Persistence:
Stores the userβs choice in localStorage to maintain consistency during the session and future visits. πΎ
- Separation of Concerns:
The hook updates two attributes on the element:data-theme
- : Indicates the applied theme, either "light" or "dark".πorigin-theme
- : Specifies the source of the theme ("user-defined" or "system"). π οΈ
- Dynamic Update:
Subscribes to changes in the system preference, updating the theme in real time (if the user has not manually set one). β‘
and origin-theme to the element of your entry file (for example, in index.html). Hereβs an example:`html
React Tailwind4 Theme Example
`>[!NOTE]
>With this initial configuration, the useHandleTheme hook will dynamically update the attributes on the
element according to the user or system preference. β
Usage Example
Below is an example of how to integrate useHandleTheme in a React component:`jsx
import { useHandleTheme } from 'react-tailwind4-theme';export const Header = () => {
const { onChangeTheme, origin, theme } = useHandleTheme();
console.log({ origin }); // user-defined - system
return (
{/ ... /}
onClick={onChangeTheme}
className="px-4 py-2 rounded bg-blue-600 text-white hover:bg-blue-700"
>
{theme === 'dark' ? (
) : (
)}
);
};
`$3
- Detects and persists the applied theme. π
- Updates the data-theme and origin-theme attributes on the
element. π
- Allows switching the theme manually via onChangeTheme. π§$3
To facilitate debugging and testing related to
prefers-color-scheme, Chrome DevTools allows you to emulate the user's color scheme preference without affecting the system-wide configuration. This is especially useful for validating the behavior of the useHandleTheme` hook. π