Add Dark Mode to Any React App in 10 Minutes
A quick, practical guide to implementing a dark mode toggle using CSS variables and React context.
February 25, 20262 min read
# Add Dark Mode to Any React App in 10 Minutes
## The Approach
We'll use CSS custom properties (variables) with a React context provider. This approach works with any styling solution — Tailwind, CSS Modules, styled-components, or plain CSS.
## Step 1: Define Your Color Tokens
```css
/* globals.css */
:root {
--bg-primary: #ffffff;
--bg-secondary: #f4f4f5;
--text-primary: #09090b;
--text-secondary: #71717a;
--border: #e4e4e7;
}
[data-theme="dark"] {
--bg-primary: #09090b;
--bg-secondary: #18181b;
--text-primary: #fafafa;
--text-secondary: #a1a1aa;
--border: #27272a;
}
```
## Step 2: Create a Theme Context
```typescript
// theme-provider.tsx
"use client";
import { createContext, useContext, useEffect, useState } from "react";
type Theme = "light" | "dark" | "system";
const ThemeContext = createContext<{
theme: Theme;
setTheme: (theme: Theme) => void;
}>({ theme: "system", setTheme: () => {} });
export function ThemeProvider({ children }: { children: React.ReactNode }) {
const [theme, setTheme] = useState("system");
useEffect(() => {
const stored = localStorage.getItem("theme") as Theme | null;
if (stored) setTheme(stored);
}, []);
useEffect(() => {
const root = document.documentElement;
const resolved =
theme === "system"
? window.matchMedia("(prefers-color-scheme: dark)").matches
? "dark"
: "light"
: theme;
root.setAttribute("data-theme", resolved);
localStorage.setItem("theme", theme);
}, [theme]);
return (
{children}
);
}
export const useTheme = () => useContext(ThemeContext);
```
## Step 3: Add a Toggle Button
```typescript
export function ThemeToggle() {
const { theme, setTheme } = useTheme();
return (
);
}
```
## Handling Flash of Incorrect Theme
Add an inline script in your HTML head to read the stored theme before React hydrates. This prevents the flash of white before dark mode kicks in.
## Accessibility Considerations
- Respect `prefers-color-scheme` by default
- Ensure sufficient contrast ratios in both themes
- Test with screen readers — theme changes should not disrupt focus
## Wrap Up
Dark mode is now expected by users. With this approach, you can add it to any React app in minutes. Make sure your Velso.dev portfolio has dark mode too — all Velso themes support it out of the box.
reactdark modecsstutorialui
Share
Ready to build your developer portfolio?
Use Velso.dev to showcase your skills, learn with AI-powered courses, and connect with clients — all in one place.
Related Articles
TutorialsFebruary 25, 2026
Build a Full-Stack App with Next.js 15, Drizzle ORM, and PostgreSQL
A complete walkthrough of building a modern full-stack application with the latest Next.js features and type-safe database access.
2 min read