Theme Switcher

Developers love dark theme but setting up the theme can be very hectic for the developers as when there are many components in your app and you have to pass your theme props very deep in the component tree where things can become ambigous.

With the help of jotai, you can setup different themes for your app in minutes. Let's take a look at this:

Initialize a theme atom with a default value.

const theme = atom('light');

Passed the atom to the useState hook.

const [appTheme, setAppTheme] = useAtom(theme);

Yes, That's all we have to do to define a global theme state which is accessible to all components of your app.

import { atom, useAtom } from 'jotai';

const theme = atom('light');

export default function Page() {
  const [appTheme, setAppTheme] = useAtom(theme);
  const handleClick = () => setAppTheme(appTheme === 'light'? 'dark': 'light');
  return (
    <div className={appTheme}>
      <h1>This is a theme switcher</h1>
      <button onClick={handleClick}>{appTheme === 'light'? 'DARK': 'LIGHT'}</button>
    </div>
  )
}
Open on CodeSandbox