Modus UI

ModeProvider

React and React Native

A React Native provider that holds the light, dark or system choice and exposes it through a useMode hook.

Holds the light, dark or system choice for the whole app. Read it anywhere below with useMode(). "system" follows the device and updates when the device changes. The provider keeps the choice in memory only; save it from onModeChange and pass it back as initialMode to remember it. Works in React and in React Native with no extra packages.

Installation

CLI

npx @modus-ui/cli add mode-provider

Manual

  1. Copy the code from the code tab, using the React or React Native switch for your project.
  2. Create a file at components/ui/mode-provider.tsx.
  3. Paste the code.

The CLI installs the React Native version in an Expo or React Native app and the React version everywhere else. In a project that targets both, keep the React file mode-provider.tsx and the React Native file mode-provider.native.tsx side by side and import ./mode-provider; Metro picks the .native file on its own.

Usage

tsx
import { Pressable, Text } from "react-native";
import { ModeProvider, useMode } from "@/components/ui/mode-provider";

function ToggleButton() {
  const { scheme, toggle } = useMode();

  return (
    <Pressable onPress={toggle}>
      <Text>Currently {scheme}</Text>
    </Pressable>
  );
}

export default function App() {
  return (
    <ModeProvider>
      <ToggleButton />
    </ModeProvider>
  );
}

Props

PropTypeDefaultDescription
initialModeMode"system"The mode to start in.
onModeChange(mode: Mode) => void-Called whenever the mode changes, so you can save it.

useMode() returns mode, the resolved scheme, setMode(mode) and toggle(), and throws outside a ModeProvider.

Comments

  • No comments yet.