MYDS Logo

    MYDS

    Beta

    useTheme

    Provides access to the current theme and method to switch themes.

    Usage

    import { useTheme } from "@govtechmy/myds-react/hooks";
     
    const { theme, setTheme } = useTheme();

    Important

    Make sure your application is wrapped with ThemeProvider before using useTheme to utilise the API provided.

    Example

    Building a Theme Switch Component

    The useTheme hook provides an easy way to manage theme states within your application. Below, we define a custom component that allows users to toggle between light and dark modes.

    theme-toggle.tsx
    import { useTheme } from "@govtechmy/myds-react/hooks";
     
    const ThemeToggle = () => {
      const { theme, setTheme } = useTheme();
     
      return (
        <button onClick={() => setTheme(theme === "light" ? "dark" : "light")}>
          Switch to {theme === "light" ? "dark" : "light"} mode
        </button>
      );
    };
     
    export { ThemeToggle }

    Declaring a Globally Accessible ThemeProvider

    To apply the theme context across the application, wrap the entire layout with the ThemeProvider. This ensures that all child components can access the theme state and toggle functionality.

    layout.tsx
    import type { ReactNode } from "react";
    import { ThemeToggleCustom, ThemeProvider } from "./ThemeToggleCustom";
     
    export default function Layout({ children }: { children: ReactNode }) {
      return (
        <ThemeProvider>
          <div className="app-container">
            <ThemeToggleCustom />
            {children}
          </div>
        </ThemeProvider>
      );
    }

    API

    useTheme

    PropTypeDefault
    theme
    string
    light
    setTheme
    (theme: string) => void
    -

    ThemeProvider

    PropTypeDefault
    defaultTheme
    string
    light
    setTheme
    (theme: string) => void
    -

    On this page