Learn how to store the user preferences.

Retrieving and setting the preferences

The settings-related actions are located in the src/lib/settings directory. These actions handle the process of setting the user preferences in the browser's cookies.

To retrieve the settings in a React Server Component you need to use the Server Function getSettingsRSC located at src/lib/settings/get-settings-rsc.ts

Createing the theme based on preferences

The root layout of the application, located at app/layout, plays a crucial role in handling user preferences and rendering the appropriate theme based on those preferences. Here's how it works:

On root layout initialization, the layout utilizes getSettingsRSC to retrieve the user's preferences from cookies. Based on the retrieved settings, the layout constructs the Joy UI theme with the appropriate theme color and primary color. This ensures that the user's selected settings are applied consistently across the entire application.

Usage example

Create a React Server Component page

// File: app/test/page.tsx
import * as React from 'react';
import { getSettingsRSC } from '@/lib/settings/get-settings-rsc';
import { setSettingsAction } from '@/lib/settings/set-settings-action';
export default function Page() {
  const settings = getSettingsRSC();
  return <ColorSchemeSwitch settings={settings.colorScheme} onSettingsUpdate={setSettingsAction} />;

Create a React Client Component switch button:

// File: app/test/color-scheme-switch.tsx
'use client';
import * as React from 'react';
export function ColorSchemeSwitch({ settings, onSettingsUpdate }) {
  const handleToggle = () => {
    const value = settings.colorScheme === 'light' ? 'dark' : 'light';
    onSettingsUpdate({ colorScheme: value });
  return <button onClick={handleToggle}>{settings.colorScheme}</button>;

On toggle the page will automatically be reloaded and the settings will be fetched from client's cookies with the updated value.