Back to cookbook

AI Prompt to Build a React Dark Mode Toggle with System Preference Detection

0 views Published

Make this prompt yours

Share

A React dark mode toggle prompt asks ChatGPT, Claude, or Gemini to generate a theme-switching component that respects the user's OS-level light/dark preference by default, lets them override it manually, and remembers that choice on their next visit. It's aimed at frontend developers who want a working toggle without re-deriving the flicker-free setup logic from scratch every time they start a new project.

The tricky part of this component isn't the toggle button itself, it's avoiding a flash of the wrong theme on page load and keeping the choice in sync across tabs. A solid prompt should ask for the user's prefers-color-scheme media query to set the initial theme, localStorage to persist an explicit override, and a storage event listener so a toggle in one tab updates others. Getting all three specified upfront saves a round of follow-up prompts to patch in behavior the first draft missed.

This pattern fits any app with a persistent header or settings panel, from marketing sites to internal dashboards. If you're also pulling the visual styling for the toggle itself from an existing design, Site to Prompt can turn a live page's rendered design into a prompt so the generated component matches your real color tokens instead of generic defaults.

Prompt template

Make this prompt yours

prompt-template
325 tokens
Role: You are a senior React developer building a reusable UI component. Context: Framework/setup: [REACT VERSION, e.g. React 18 with Vite, Next.js App Router] Styling approach: [CSS variables / Tailwind CSS dark class / CSS-in-JS library] Component location/usage: [where the toggle will live, e.g. app header, settings page] Task: Build a dark mode toggle component with this exact behavior: 1. On first load, detect the user's OS preference via the `prefers-color-scheme` media query and use it as the initial theme, applied before the main content paints (no flash of the wrong theme). 2. If the user has previously made an explicit choice, that stored choice overrides the OS preference on future visits. 3. Persist the user's explicit choice in [STORAGE MECHANISM, e.g. localStorage]. 4. Listen for theme changes made in other open tabs and update this tab's theme to match. 5. Expose the current theme and a toggle function via [CONTEXT/HOOK NAME, e.g. a useTheme hook] so other components can read and react to it. Constraints: - Use [STYLING APPROACH] to apply the theme, not inline style objects - Include accessible labeling (aria-label or visible text) that reflects the current state - Keep the component dependency-free unless [ALLOWED LIBRARIES] are specified Output format: Return the full component code in a fenced code block, followed by a short usage example showing how to wrap the app and consume the hook elsewhere.

Want it sharper? Optimize this prompt with Prompt Optimizer, check it with the Prompt Debugger or shorten it with the Token Optimizer.

Example input

example-input
58 tokens
Framework/setup: React 18 with Vite Styling approach: Tailwind CSS dark class on the html element Component location/usage: top-right corner of the app header Storage mechanism: localStorage Context/hook name: useTheme Allowed libraries: none beyond React itself

When to use it

  • Adding a theme switcher to a new React app that currently has no dark mode support
  • Replacing a dark mode toggle that causes a visible flash of the wrong theme on load
  • Building a settings panel where the user's theme choice needs to persist across sessions and tabs
  • Standardizing a reusable theme toggle component shared across multiple pages or micro-frontends

Best practices

  • Specify how the initial theme should be determined before any content paints, to avoid a flash of the wrong theme
  • Ask explicitly for a storage event listener so a theme change in one open tab updates other open tabs
  • Request that the component expose the current theme through a context or hook, not just a local toggle button, so other components can read it
  • Tell the model which CSS approach you use (CSS variables, Tailwind's dark class, CSS-in-JS) so the generated code matches your existing styling system

Common mistakes

  • Letting the initial theme default to light or dark without checking prefers-color-scheme first
  • Storing the theme choice only in component state, so it resets on every page reload
  • Forgetting to update the toggle's accessible label and icon so screen reader users know which mode is active
  • Hardcoding colors inline instead of toggling a class or CSS variable, which makes the component hard to restyle later

FAQs

How do I stop a dark mode toggle from flashing the wrong theme on page load?

Read the theme synchronously before React renders, either from localStorage or the prefers-color-scheme media query, and apply the resulting class to the html element in a blocking inline script or during server render, rather than waiting for a useEffect to run after paint.

Should I store the dark mode preference in localStorage or a cookie?

localStorage is simpler for a client-only React app. Use a cookie instead if a server needs to know the theme at render time, such as in a Next.js app that server-renders the correct class to avoid any flash at all.

How do I keep dark mode in sync across multiple open tabs?

Listen for the browser's storage event, which fires in other tabs whenever localStorage changes. When it fires with your theme key, update that tab's state to match instead of requiring a manual refresh.

Which Cuelara tool helps me match this toggle to my site's existing design?

Site to Prompt — measures a real rendered page and turns its colors, spacing, and typography into a prompt, so a generated toggle's styling matches your actual design instead of generic defaults.

Found this prompt useful? Share it.

Share

More in React Prompt Recipes

React Prompt Recipes

AI Prompt to Build a React Billing Dashboard Component Using Stripe's MCP Server

This prompt is for frontend developers who need to build a React billing dashboard component that shows a customer's live subscription, invo…

ROLE:
You are a senior React/TypeScript developer building a billing dashboard component for a SaaS product.

CONTEXT:
The component should display billing data for a customer, retrieved via Stripe's MCP server: [LIST_DATA_NEEDED_E.G._SUBSCRIPTION_PLAN_NEXT_CHARGE_DATE_PAYMENT_METHOD_RECENT_INVOICES]
Framework/styling: [REACT_VERSION_AND_STYLING_APPROACH_E.G._TAILWIND_CSS_MODULES]

CONSTRAINTS:
- Handle these billing states explicitly: [LIST_STATES_E.G._ACTIVE_PAST_DUE_CANCELED_PENDING_NO_PAYMENT_METHOD]
- Show a loading skeleton while data is being fetched, and a clear error state if the fetch fails
- Format currency and dates using the customer's actual locale/currency, not a hardcoded format
- Separate the data-fetching hook from the presentational component

OUTPUT FORMAT:
1. A short explanation of the component's structure (hook + presentational component)
2. The full TypeScript code, in a single fenced code block, with comments marking where each billing state is handled
3. A one-line note on any assumption you made about the data shape returned by the MCP server

Make this prompt yours

React Prompt Recipes

AI Prompt to Build a React Kanban Board With Drag-and-Drop

This prompt gives ChatGPT, Claude, or Gemini a complete specification for building a React Kanban board with drag and drop column reordering…

You are a senior React developer specializing in accessible, production-ready UI components.

Context:
- Framework: [REACT VERSION, e.g. React 18 with TypeScript]
- Drag-and-drop library: [LIBRARY NAME, e.g. @dnd-kit/core]
- Styling approach: [e.g. Tailwind CSS, CSS Modules, styled-components]
- Columns or workflow stages: [LIST OF COLUMN NAMES, e.g. Backlog, In Progress, Review, Done]
- State source: [e.g. local state, Zustand store, REST API endpoint]

Build a Kanban board component with the following requirements:
1. Render one column per workflow stage listed above, each showing its card count
2. Support dragging cards between columns and reordering cards within a column
3. Support keyboard-based reordering, not mouse-only interaction, for accessibility
4. Identify cards by a stable [ID FIELD NAME] field, never by array index
5. Call a [CALLBACK NAME] function on every successful move, passing the card id, source column, destination column, and new index
6. Show an optimistic UI update immediately, then roll back if [CALLBACK NAME] rejects
7. Handle empty columns and drops outside any valid column gracefully

Output format:
- The main board component
- Column and Card subcomponents
- Any custom hooks used for drag state
- A short usage example showing how to wire [CALLBACK NAME] to a real API call
- Brief notes on any library-specific setup required, such as providers, context, or CSS imports

Make this prompt yours

React Prompt Recipes

AI Prompt for an Accessible React Autocomplete Combobox

This prompt is for developers asking Claude , ChatGPT , or Gemini to generate a React autocomplete combobox component, the input plus dropdo…

Generate a React component with the following specification.

ROLE
- You are a frontend engineer who writes accessible, production-ready React components.

COMPONENT
- A searchable autocomplete combobox named [COMPONENT NAME].
- Props: options ([OPTION SHAPE, e.g. array of {id, label}]), value, onChange, placeholder.
- Controlled component: value and onChange are provided by the parent; do not manage selected value as internal-only state.

ACCESSIBILITY REQUIREMENTS
- Use the ARIA 1.2 combobox pattern: role="combobox" on the input, role="listbox" on the options container, role="option" on each item, and aria-activedescendant to track the highlighted option.
- Support keyboard interaction: ArrowDown/ArrowUp to move highlight, Enter to select the highlighted option, Escape to close the list, Home/End to jump to first/last option.
- Announce the number of matching results to screen readers when the list updates.

BEHAVIOR
- Filter options client-side, debounced by [DEBOUNCE MS, e.g. 150]ms.
- Close the dropdown on click outside or on Escape.
- If no options match, display [EMPTY STATE MESSAGE] inside the listbox instead of hiding it.

OUTPUT FORMAT
- A single functional component using hooks, written in [TYPESCRIPT OR JAVASCRIPT], with inline comments marking each accessibility feature.

Make this prompt yours