A modern, production-ready template for building web applications with React 19, TypeScript, Vite, Tailwind CSS v4, React Router for navigation, React Query for server state management, React Hook Form with Zod validation, and a comprehensive theming system with dark mode support.
| Section | Description |
|---|---|
| β¨ What's New | Latest features and improvements |
| π Features | Core capabilities and tech stack |
| π Technologies | Complete tech stack overview |
| ποΈ Getting Started | Installation and setup |
| π Project Structure | File organization |
| β‘ Scripts | Development commands |
| π― App Features | Comprehensive single page demos |
| π§ Routing | React Router setup |
| π State Management | React Query integration |
| π Forms | Form validation with Zod |
| π¨ Theme System | Comprehensive theming guide |
| π Dark Mode | Dark mode setup |
| π οΈ Dev Tools | ESLint, Prettier, git hooks |
| β‘ Performance | Speed optimizations |
| πΎ Storage | Local and secure storage hooks |
| π Deployment | Deploy guides |
| π¦ Dependencies | Package management |
| π§ͺ Testing | Testing setup |
| π€ Contributing | Development workflow |
| π Troubleshooting | Common issues and solutions |
| π License | Project license |
| π Acknowledgments | Credits and thanks |
This template features a comprehensive single-page application structure with:
- π Consolidated HomePage - All features, forms, and demos in one comprehensive page
- π― Complete Feature Showcase - Theme system, form validation, and interactive examples
- π Integrated Form Demos - Login and registration forms with real-time validation
- π Enhanced Error Boundary - Improved UI with better button alignment and styling
- π Advanced Pre-Push Hooks - Auto-fix capabilities for ESLint and Prettier with change staging
- β‘ Performance Optimizations - Smart caching and conditional builds
- π οΈ Streamlined Navigation - Simplified single-page structure for focused development
- π¨ Enhanced Developer Experience - Automated code quality checks with auto-fixing
- π§ React Router v7: Full client-side routing with nested routes and layouts
- π React Query: Powerful server state management with caching and background updates
- π React Hook Form: Performant forms with minimal re-renders
- β Zod Validation: Type-safe schema validation for forms and APIs
- π¨ Lucide React: Beautiful, customizable icon library with 1000+ icons
- π± Responsive Pages: Pre-built pages showcasing all features
- ποΈ Scalable Architecture: Feature-based organization with clean imports
- π¦ Path Mapping: Clean imports with
@/*aliases (e.g.,@/components/ui)
- π¨ Complete theming system with semantic color variables
- π Dark mode support out of the box
- π± Responsive design ready
- π Optimized for Tailwind CSS v4
This template includes a configured path mapping system for clean, maintainable imports:
// β
Clean imports with path mapping
import { Button } from '@/components/ui';
import { Layout } from '@/components/layout';
import { useAuth } from '@/features/auth';
import { API_CONFIG } from '@/utils/constants';
import { formatDate } from '@/utils/helpers';
// β
Barrel exports for organized imports
import { Toast, ToastContainer } from '@/components/ui';
import { ErrorBoundary } from '@/components';
// β Instead of messy relative imports
import Button from '../../../components/ui/Button';
import Layout from '../../components/layout/Layout';Path Mapping Configuration:
@/*maps tosrc/*(configured intsconfig.app.jsonandvite.config.ts)- Index files provide clean barrel exports
- IntelliSense and auto-imports work seamlessly
- βοΈ React 19 with TypeScript
- β‘οΈ Vite for fast development and builds
- π§Ή ESLint and Prettier for code quality
- πͺ Husky and lint-staged for pre-commit hooks
- β‘ Performance optimizations with intelligent caching
This template combines the following technologies to provide a modern development experience:
- React 19: Latest version with improved performance and new features
- TypeScript: Static type checking for more robust code
- React Router v7: Modern client-side routing with data loading
- React Query (TanStack Query): Server state management with intelligent caching
- React Hook Form: High-performance forms with minimal re-renders
- Zod: TypeScript-first schema validation
- Lucide React: Beautiful, customizable icon library
- Vite: Next generation frontend tooling for fast development and optimized builds
- Tailwind CSS v4: Utility-first CSS framework with built-in dark mode support
- ESLint: Linting utility for identifying and fixing code problems (with caching)
- Prettier: Code formatter for consistent styling
- Husky: Git hooks to enforce code quality checks before commits
- lint-staged: Run linters on git staged files only
- ESLint caching: 70% faster linting with intelligent cache
- TypeScript incremental compilation: 95% faster type checking
- Smart git hooks: Conditional builds and optimized pre-commit checks
-
Clone this repository:
git clone https://github.com/YousifAbozid/template-react-ts my-project cd my-project -
Install dependencies:
npm install # or yarn install # or pnpm install
-
Start the development server:
npm run dev # or yarn dev # or pnpm dev
-
Open your browser and visit http://localhost:3000
This template follows a scalable, feature-based architecture designed for maintainability and future growth. See STRUCTURE.md for detailed documentation.
template-react-ts/
βββ .husky/ # Git hooks configuration
β βββ pre-commit # Lint staged files before commit
β βββ pre-push # Enhanced with auto-fix capabilities
βββ src/
β βββ π app/ # Application configuration and setup
β β βββ App.tsx # Main app component
β β βββ providers.tsx # Global providers (React Query, Toast, etc.)
β β βββ router.tsx # Application routing configuration
β β βββ index.ts # App exports
β βββ π components/ # Reusable components organized by type
β β βββ π ui/ # Basic UI components
β β β βββ Toast.tsx
β β β βββ ToastContainer.tsx
β β β βββ index.ts
β β βββ π layout/ # Layout-specific components
β β β βββ Layout.tsx
β β β βββ ThemeToggle.tsx
β β β βββ index.ts
β β βββ ErrorBoundary.tsx # Global error boundary
β β βββ index.ts # Component exports
β βββ π contexts/ # React contexts
β β βββ ToastContext.tsx
β βββ π features/ # Feature-based modules (self-contained)
β β βββ README.md # Feature architecture documentation
β βββ π hooks/ # Custom React hooks
β β βββ useDebounce.ts
β β βββ index.ts
β βββ π lib/ # Third-party library configurations
β β βββ query-client.ts
β βββ π pages/ # Page components
β β βββ HomePage.tsx
β β βββ NotFoundPage.tsx
β βββ π styles/ # Global styles and themes
β β βββ globals.css # Theme system & global styles
β βββ π types/ # TypeScript type definitions
β β βββ index.ts # Common types (API, UI, Theme, etc.)
β βββ π utils/ # Utility functions and constants
β β βββ constants.ts # Application constants
β β βββ helpers.ts # Utility functions
β β βββ index.ts
β βββ main.tsx # Application entry point
β βββ vite-env.d.ts # Vite type definitions
βββ public/ # Static assets
βββ index.html # HTML template
βββ vite.config.ts # Vite configuration
βββ tsconfig.json # TypeScript configuration
βββ eslint.config.js # ESLint configuration
βββ STRUCTURE.md # Detailed architecture documentation
βββ PERFORMANCE.md # Performance optimization guide
βββ package.json # Project dependencies and scripts
- π― Feature-Based: Organized for scalability and team development
- π¦ Clean Imports: Path mapping (
@/*) for maintainable code - π¨ Component Organization: UI, layout, and feature-specific separation
- π Type Safety: Centralized TypeScript definitions
- β‘ Performance: Optimized structure for build and runtime performance
π Detailed Guide: See STRUCTURE.md for comprehensive architecture documentation, migration guide, and best practices.
The template includes the following npm scripts organized by category:
npm run dev: Start the development server with HMRnpm run preview: Preview the production build locally
npm run build: Type-check and build the app for productionnpm run type-check: Run TypeScript type checking (incremental, cached)
npm run lint: Run ESLint to check for code issues (cached)npm run lint:fix: Run ESLint and automatically fix issues (cached)npm run format:all: Run Prettier to format all filesnpm run format:check: Check if files are properly formatted
npm run fix-all: Run both lint:fix and format:all to fix all issuesnpm run fix-staged: Run lint-staged manually (same as pre-commit hook)
npm run upgrade: Update all dependencies to their latest versions
- ESLint caching: 70% faster linting on subsequent runs
- TypeScript incremental: 95% faster type checking
- Smart git hooks: Conditional execution saves development time
π For detailed performance information, see PERFORMANCE.md
This template features a comprehensive single-page application that demonstrates real-world usage patterns:
A complete showcase including all features in one optimized page:
- Hero Section: Feature highlights with interactive badges
- Technology Showcase: Complete overview of included technologies
- Theme System Demo: Interactive examples of the complete theming system
- Form Validation Demo: Live React Hook Form + Zod examples
- Getting Started Guide: Step-by-step setup instructions
- Code Examples: Real implementation patterns and usage
- Performance Features: Browser support and optimization details
Built-in form demonstrations with React Hook Form + Zod:
- Login Form: Email validation, password requirements, real-time feedback
- Registration Form: Complex validation rules, password confirmation
- Error Handling: Form-level and field-level error display with styling
- TypeScript Integration: Fully typed form schemas and data
// Example: Type-safe form with Zod validation
const loginSchema = z.object({
email: z.string().email('Invalid email address'),
password: z.string().min(8, 'Password must be at least 8 characters'),
});
type LoginFormData = z.infer<typeof loginSchema>;Interactive theme demonstrations:
- Color Palette: Visual representation of all theme variables
- Component Examples: Buttons, forms, alerts in different states
- Code Snippets: Real usage patterns for theming
- Responsive Design: Mobile-first examples and breakpoints
- Responsive Navigation: Desktop and mobile-optimized navigation
- Active States: Visual indicators for current page
- Theme Integration: Navigation respects light/dark mode
- Accessibility: Keyboard navigation and screen reader support
Reusable components demonstrated throughout the app:
- Form Fields: Input, Select, Textarea with validation states
- Buttons: Primary, secondary, outline variants
- Cards: Content containers with proper spacing
- Alerts: Success, warning, error message components
- Code Blocks: Syntax-highlighted code examples
- Loading States: Skeletons and spinners
The template includes a complete routing setup with React Router v7:
// App.tsx - Clean, organized application setup
import App from './app';
export default App;The app is now organized with a clear separation of concerns:
app/App.tsx: Main application componentapp/providers.tsx: Global providers setupapp/router.tsx: Application routing configuration
Shared layout with navigation:
// components/layout/Layout.tsx
import { Outlet, Link, useLocation } from 'react-router-dom';
import ThemeToggle from './ThemeToggle';
const Layout = () => {
const location = useLocation();
return (
<div>
<nav>
{/* Navigation with active states */}
<Link to="/" className={location.pathname === '/' ? 'active' : ''}>
Home
</Link>
<ThemeToggle />
</nav>
<main>
<Outlet /> {/* Child routes render here */}
</main>
<footer>{/* Shared footer */}</footer>
</div>
);
};
export default Layout;- Active States: Visual feedback for current route
- Mobile Responsive: Collapsible navigation for mobile devices
- Theme Integration: Navigation respects light/dark mode
- TypeScript: Fully typed route parameters and navigation
Complete server state management with TanStack Query:
// App configuration with providers
// app/providers.tsx
import { QueryClientProvider } from '@tanstack/react-query';
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
import { ToastProvider } from '@/contexts/ToastContext';
import ToastContainer from '@/components/ui/ToastContainer';
import { queryClient } from '@/lib/query-client';
export function AppProviders({ children }: { children: React.ReactNode }) {
return (
<ToastProvider>
<QueryClientProvider client={queryClient}>
{children}
<ReactQueryDevtools initialIsOpen={false} />
<ToastContainer />
</QueryClientProvider>
</ToastProvider>
);
}// Custom hooks for API calls
const usePosts = () => {
return useQuery({
queryKey: ['posts'],
queryFn: async () => {
const response = await fetch(
'https://jsonplaceholder.typicode.com/posts'
);
if (!response.ok) throw new Error('Failed to fetch posts');
return response.json();
},
});
};
const useCreatePost = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (newPost: CreatePostData) => {
const response = await fetch(
'https://jsonplaceholder.typicode.com/posts',
{
method: 'POST',
body: JSON.stringify(newPost),
headers: { 'Content-Type': 'application/json' },
}
);
return response.json();
},
onSuccess: () => {
// Invalidate and refetch posts
queryClient.invalidateQueries({ queryKey: ['posts'] });
},
});
};Type-safe form validation with excellent performance:
import { z } from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form';
// Define validation schema
const registrationSchema = z
.object({
email: z.string().email('Invalid email address'),
password: z
.string()
.min(8, 'Password must be at least 8 characters')
.regex(
/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/,
'Password must contain uppercase, lowercase, and number'
),
confirmPassword: z.string(),
name: z.string().min(2, 'Name must be at least 2 characters'),
})
.refine(data => data.password === data.confirmPassword, {
message: "Passwords don't match",
path: ['confirmPassword'],
});
type RegistrationFormData = z.infer<typeof registrationSchema>;const RegistrationForm = () => {
const {
register,
handleSubmit,
formState: { errors, isSubmitting },
} = useForm<RegistrationFormData>({
resolver: zodResolver(registrationSchema),
});
const onSubmit = async (data: RegistrationFormData) => {
// Handle form submission
console.log('Form data:', data);
};
return (
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
<div>
<input
{...register('email')}
type="email"
placeholder="Email"
className="w-full p-2 border rounded"
/>
{errors.email && (
<p className="text-red-500 text-sm">{errors.email.message}</p>
)}
</div>
<button
type="submit"
disabled={isSubmitting}
className="w-full bg-blue-500 text-white p-2 rounded"
>
{isSubmitting ? 'Submitting...' : 'Register'}
</button>
</form>
);
};- Type Safety: Full TypeScript integration
- Real-time Validation: Instant feedback on field changes
- Error Handling: Field-level and form-level error display
- Performance: Minimal re-renders with uncontrolled components
- Accessibility: Proper ARIA labels and error associations
This template includes a comprehensive theming system with semantic color variables designed for both light and dark modes. The system provides a foundation for consistent UI design and easy customization.
The theming system is built on these core principles:
- Semantic Color Variables: Instead of using generic color names, colors are named by their purpose (e.g.,
l-bg-1for primary light background) - Mode-Aware Design: Each color has both light and dark mode variants
- Hierarchical Structure: Colors follow a hierarchy (primary, secondary, tertiary) for consistent visual layering
- CSS Custom Properties: Leverages modern CSS variables for dynamic theming
- Tailwind Integration: Works seamlessly with Tailwind CSS v4's
@themedirective
The color system is organized into logical categories:
l-bg-1/d-bg-1: Primary backgrounds (main content areas)l-bg-2/d-bg-2: Secondary backgrounds (cards, panels)l-bg-3/d-bg-3: Tertiary backgrounds (subtle sections)l-bg-hover/d-bg-hover: Hover state backgrounds
l-text-1/d-text-1: Primary text (headings, main content)l-text-2/d-text-2: Secondary text (subheadings, descriptions)l-text-3/d-text-3: Tertiary text (muted, captions)l-text-inv/d-text-inv: Inverted text (text on contrasting backgrounds)
accent-1: Primary brand coloraccent-2: Secondary brand coloraccent-success: Success states and positive feedbackaccent-warning: Warning states and alertsaccent-danger: Error states and destructive actions
border-l/border-d: Border colors for light/dark modesshadow-l/shadow-d: Box shadow colors for elevation effects
Apply theme colors using Tailwind utility classes with automatic dark mode support:
// Auto-switching backgrounds
<div className="bg-l-bg-1 dark:bg-d-bg-1">
Main content area
</div>
// Auto-switching text
<h1 className="text-l-text-1 dark:text-d-text-1">
Primary heading
</h1>
// Mode-independent accent colors
<button className="bg-accent-1 text-white">
Primary Action
</button>
// Combined theme-aware styling
<div className="bg-l-bg-2 dark:bg-d-bg-2 border border-border-l dark:border-border-d rounded-lg p-4">
<h3 className="text-l-text-1 dark:text-d-text-1">Card Title</h3>
<p className="text-l-text-2 dark:text-d-text-2">Card description</p>
</div>// Button with hover states and theme awareness
<button className="
bg-accent-1 hover:bg-accent-2
text-l-text-inv dark:text-d-text-inv
px-4 py-2 rounded-md
transition-colors duration-200
shadow-lg shadow-shadow-l dark:shadow-shadow-d
">
Interactive Button
</button>
// Input field with theme support
<input className="
bg-l-bg-1 dark:bg-d-bg-1
text-l-text-1 dark:text-d-text-1
border border-border-l dark:border-border-d
focus:border-accent-1
rounded px-3 py-2
placeholder:text-l-text-3 dark:placeholder:text-d-text-3
"
placeholder="Enter your text..." />// Success alert
<div className="bg-l-bg-2 dark:bg-d-bg-2 border-l-4 border-accent-success p-4 rounded">
<div className="flex items-center">
<span className="text-accent-success">β</span>
<p className="ml-2 text-l-text-1 dark:text-d-text-1">Success message</p>
</div>
</div>
// Warning alert
<div className="bg-l-bg-3 dark:bg-d-bg-3 border border-accent-warning rounded p-3">
<p className="text-accent-warning font-medium">Warning:</p>
<p className="text-l-text-2 dark:text-d-text-2">This action cannot be undone</p>
</div>
// Error state
<div className="bg-l-bg-1 dark:bg-d-bg-1 border border-accent-danger rounded p-3">
<p className="text-accent-danger">Error: Something went wrong</p>
</div>// Navigation bar
<nav className="bg-l-bg-2 dark:bg-d-bg-2 border-b border-border-l dark:border-border-d">
<div className="px-4 py-3">
<ul className="flex space-x-4">
<li>
<a href="#" className="text-l-text-1 dark:text-d-text-1 hover:text-accent-1">
Home
</a>
</li>
<li>
<a href="#" className="text-l-text-2 dark:text-d-text-2 hover:text-l-text-1 dark:hover:text-d-text-1">
About
</a>
</li>
</ul>
</div>
</nav>
// Sidebar
<aside className="bg-l-bg-3 dark:bg-d-bg-3 w-64 min-h-screen p-4">
<h2 className="text-l-text-1 dark:text-d-text-1 font-bold mb-4">Sidebar</h2>
<div className="space-y-2">
<div className="p-2 rounded hover:bg-l-bg-hover dark:hover:bg-d-bg-hover">
<span className="text-l-text-2 dark:text-d-text-2">Menu Item</span>
</div>
</div>
</aside>The theme is defined in src/styles/globals.css using Tailwind CSS v4's @theme directive:
@theme {
/* Your color variables go here */
--color-l-bg-1: #ffffff;
--color-accent-1: #58a6ff;
/* etc. */
}To change existing colors, simply update the corresponding CSS custom property:
@theme {
/* Change primary brand color */
--color-accent-1: #ff6b6b; /* Your new primary color */
--color-accent-2: #ee5a52; /* Darker variant for hover states */
/* Customize light mode backgrounds */
--color-l-bg-1: #fafafa; /* Slightly off-white */
--color-l-bg-2: #f0f0f0; /* Light gray */
/* Customize dark mode backgrounds */
--color-d-bg-1: #1a1a1a; /* Warmer dark */
--color-d-bg-2: #2d2d2d; /* Medium dark */
/* Update text colors for better contrast */
--color-l-text-1: #1a1a1a; /* Softer black */
--color-d-text-1: #f5f5f5; /* Softer white */
}You can extend the system with your own semantic colors:
@theme {
/* Existing colors... */
/* Add new brand colors */
--color-brand-primary: #3b82f6;
--color-brand-secondary: #8b5cf6;
--color-brand-tertiary: #06b6d4;
/* Add specialized semantic colors */
--color-info: #0ea5e9;
--color-tip: #22c55e;
--color-feature: #f59e0b;
/* Add surface colors for different content types */
--color-surface-code: #f8fafc;
--color-surface-highlight: #fef3c7;
--color-surface-muted: #f1f5f9;
/* Add status-specific colors */
--color-status-online: #10b981;
--color-status-away: #f59e0b;
--color-status-offline: #6b7280;
}Then use them in your components:
// Using new brand colors
<div className="bg-brand-primary text-white p-4">
Primary brand section
</div>
// Using specialized semantic colors
<div className="bg-surface-code p-3 rounded border-l-4 border-info">
<code className="text-info">console.log('Hello, world!');</code>
</div>
// Status indicators
<span className="inline-block w-3 h-3 rounded-full bg-status-online"></span>
<span className="ml-2 text-l-text-1 dark:text-d-text-1">Online</span>You can create multiple theme variations for different sections or contexts:
@theme {
/* Default theme colors... */
/* Admin panel theme */
--color-admin-bg-primary: #1e293b;
--color-admin-bg-secondary: #334155;
--color-admin-accent: #f97316;
--color-admin-text: #f1f5f9;
/* Marketing theme */
--color-marketing-gradient-start: #667eea;
--color-marketing-gradient-end: #764ba2;
--color-marketing-highlight: #fbbf24;
/* Blog theme */
--color-blog-bg-article: #fefefe;
--color-blog-text-body: #374151;
--color-blog-accent-link: #2563eb;
}Apply theme variants using specific classes:
// Admin panel with custom theme
<div className="bg-admin-bg-primary text-admin-text min-h-screen">
<header className="bg-admin-bg-secondary p-4">
<h1 className="text-admin-accent">Admin Dashboard</h1>
</header>
</div>
// Marketing section with gradient
<section className="bg-linear-to-r from-marketing-gradient-start to-marketing-gradient-end">
<h2 className="text-white">Marketing Content</h2>
<span className="text-marketing-highlight">Special Offer!</span>
</section>Create multiple complete color schemes:
@theme {
/* Base theme colors... */
/* High Contrast Theme */
--color-hc-bg-1: #000000;
--color-hc-bg-2: #1a1a1a;
--color-hc-text-1: #ffffff;
--color-hc-text-2: #f0f0f0;
--color-hc-accent: #ffff00;
/* Sepia Theme */
--color-sepia-bg-1: #f7f3e9;
--color-sepia-bg-2: #f0ead6;
--color-sepia-text-1: #5d4e37;
--color-sepia-text-2: #8b7355;
--color-sepia-accent: #cd853f;
/* Blue Light Theme */
--color-blue-bg-1: #1a1f36;
--color-blue-bg-2: #242946;
--color-blue-text-1: #e1e5f2;
--color-blue-text-2: #b8c4db;
--color-blue-accent: #4dabf7;
}Extend the ThemeToggle component to support multiple themes:
// Enhanced theme toggle component
import { useState, useEffect } from 'react';
import useLocalStorage from 'use-local-storage';
type Theme = 'light' | 'dark' | 'high-contrast' | 'sepia';
const AdvancedThemeToggle = () => {
const [theme, setTheme] = useLocalStorage<Theme>('advanced-theme', 'light');
useEffect(() => {
// Remove all theme classes
document.documentElement.className = '';
// Add current theme class
document.documentElement.classList.add(theme);
}, [theme]);
const themes: { value: Theme; label: string; icon: string }[] = [
{ value: 'light', label: 'Light', icon: 'βοΈ' },
{ value: 'dark', label: 'Dark', icon: 'π' },
{ value: 'high-contrast', label: 'High Contrast', icon: 'π²' },
{ value: 'sepia', label: 'Sepia', icon: 'π' },
];
return (
<select
value={theme}
onChange={e => setTheme(e.target.value as Theme)}
className="bg-l-bg-2 dark:bg-d-bg-2 text-l-text-1 dark:text-d-text-1 border border-border-l dark:border-border-d rounded px-3 py-2"
>
{themes.map(({ value, label, icon }) => (
<option key={value} value={value}>
{icon} {label}
</option>
))}
</select>
);
};Dynamically update theme colors using JavaScript:
// Theme customization hook
const useThemeCustomization = () => {
const updateThemeColor = (property: string, value: string) => {
document.documentElement.style.setProperty(`--color-${property}`, value);
};
const resetTheme = () => {
// Reset to default values
const defaults = {
'l-bg-1': '#ffffff',
'accent-1': '#58a6ff',
// ... other defaults
};
Object.entries(defaults).forEach(([property, value]) => {
updateThemeColor(property, value);
});
};
return { updateThemeColor, resetTheme };
};
// Theme customizer component
const ThemeCustomizer = () => {
const { updateThemeColor } = useThemeCustomization();
const [primaryColor, setPrimaryColor] = useState('#58a6ff');
const handleColorChange = (color: string) => {
setPrimaryColor(color);
updateThemeColor('accent-1', color);
};
return (
<div className="p-4 bg-l-bg-2 dark:bg-d-bg-2 rounded-lg">
<label className="block text-l-text-1 dark:text-d-text-1 mb-2">
Primary Color:
</label>
<input
type="color"
value={primaryColor}
onChange={e => handleColorChange(e.target.value)}
className="w-full h-10 rounded border border-border-l dark:border-border-d"
/>
</div>
);
};Ensure your custom themes meet accessibility standards:
@theme {
/* Ensure sufficient contrast ratios */
--color-l-bg-1: #ffffff; /* Background */
--color-l-text-1: #1a1a1a; /* Text - should have 4.5:1 contrast ratio */
/* Test your colors using tools like: */
/* - WebAIM Contrast Checker */
/* - Chrome DevTools Accessibility panel */
/* - axe accessibility checker */
}Create a comprehensive test page to validate your theme:
// ThemeTestPage component
const ThemeTestPage = () => {
return (
<div className="p-8 space-y-8">
{/* Background layers test */}
<section className="space-y-4">
<h2 className="text-l-text-1 dark:text-d-text-1 text-xl font-bold">
Background Layers
</h2>
<div className="bg-l-bg-1 dark:bg-d-bg-1 p-4 border border-border-l dark:border-border-d">
<p className="text-l-text-1 dark:text-d-text-1">
Primary background (l-bg-1/d-bg-1)
</p>
<div className="mt-2 bg-l-bg-2 dark:bg-d-bg-2 p-4">
<p className="text-l-text-1 dark:text-d-text-1">
Secondary background (l-bg-2/d-bg-2)
</p>
<div className="mt-2 bg-l-bg-3 dark:bg-d-bg-3 p-4">
<p className="text-l-text-1 dark:text-d-text-1">
Tertiary background (l-bg-3/d-bg-3)
</p>
</div>
</div>
</div>
</section>
{/* Text hierarchy test */}
<section className="space-y-4">
<h2 className="text-l-text-1 dark:text-d-text-1 text-xl font-bold">
Text Hierarchy
</h2>
<div className="bg-l-bg-1 dark:bg-d-bg-1 p-4">
<h1 className="text-l-text-1 dark:text-d-text-1 text-2xl">
Primary text (l-text-1/d-text-1)
</h1>
<p className="text-l-text-2 dark:text-d-text-2 text-lg">
Secondary text (l-text-2/d-text-2)
</p>
<p className="text-l-text-3 dark:text-d-text-3">
Tertiary text (l-text-3/d-text-3)
</p>
</div>
</section>
{/* Accent colors test */}
<section className="space-y-4">
<h2 className="text-l-text-1 dark:text-d-text-1 text-xl font-bold">
Accent Colors
</h2>
<div className="grid grid-cols-2 md:grid-cols-5 gap-4">
<button className="bg-accent-1 text-white p-3 rounded">
Primary
</button>
<button className="bg-accent-2 text-white p-3 rounded">
Secondary
</button>
<button className="bg-accent-success text-white p-3 rounded">
Success
</button>
<button className="bg-accent-warning text-white p-3 rounded">
Warning
</button>
<button className="bg-accent-danger text-white p-3 rounded">
Danger
</button>
</div>
</section>
</div>
);
};- Maintain Contrast Ratios: Always test that text remains readable against background colors
- Use Semantic Naming: Choose color variable names that describe purpose, not appearance
- Test Both Modes: Ensure your customizations work in both light and dark modes
- Consider Color Blindness: Test your themes with color blindness simulators
- Document Your Changes: Keep track of customizations for team collaboration
- Version Your Themes: Use version control to track theme evolution
- Performance: Avoid excessive CSS custom property updates for better performance
This comprehensive theming system provides the foundation for creating beautiful, accessible, and maintainable user interfaces that adapt to your specific design requirements.
This template includes a ready-to-use dark mode implementation:
-
Theme Toggle Component: Located at
src/components/layout/ThemeToggle.tsx, this component provides a button to switch between light and dark modes. -
Local Storage: User preference is saved to local storage so it persists between visits.
-
System Preference Detection: The template automatically detects the user's system preference for dark/light mode on first visit.
-
Implementation Example:
import { ThemeToggle } from '@/components/layout';
function MyComponent() {
return (
<div className="bg-l-bg-1 dark:bg-d-bg-1 text-l-text-1 dark:text-d-text-1">
<h1>My Component</h1>
<ThemeToggle />
</div>
);
}This template uses ESLint to enforce code quality with intelligent caching for optimal performance. The configuration is in eslint.config.js and includes:
- React recommended rules
- TypeScript integration
- Import order rules
- React Hooks rules
- Performance caching - 70% faster linting on subsequent runs
To run ESLint:
npm run lint # Check for issues (cached)
npm run lint:fix # Fix issues automatically (cached)Caching Details:
- Cache file:
.eslintcache(automatically managed) - First run: ~6 seconds, subsequent runs: ~2.5 seconds
- Only re-lints files that have changed since last run
Prettier ensures consistent code formatting. Configuration includes modern settings for optimal development experience:
{
"singleQuote": true,
"semi": true,
"tabWidth": 2,
"printWidth": 80,
"trailingComma": "es5",
"arrowParens": "avoid",
"endOfLine": "lf"
}To run Prettier:
npm run format:all # Format all files
npm run format:check # Check formattingTypeScript compilation is optimized with incremental builds:
npm run type-check # Incremental type checking (95% faster)Performance Benefits:
- Cache file:
.tsbuildinfo(automatically managed) - Only type-checks changed files and their dependencies
- Massive speed improvement on large codebases
The template uses optimized git hooks for maximum development speed:
Pre-commit Hook (.husky/pre-commit):
- Runs lint-staged with caching enabled
- Only processes staged files (not entire codebase)
- ESLint and Prettier run with caching for speed
Pre-push Hook (.husky/pre-push):
- Enhanced auto-fix capabilities: Automatically fixes ESLint and Prettier issues
- Smart change detection: Only processes files that have actually changed
- Automatic staging: Auto-stages fixed files for seamless workflow
- Smart build verification: Only builds if source files changed after fixes
- Clear feedback: Notifies about applied fixes and build decisions
lint-staged configuration:
{
"*.{js,jsx,ts,tsx}": [
"eslint --fix --cache --cache-location .eslintcache",
"prettier --write"
],
"*.{json,md}": ["prettier --write"]
}This ensures that all committed code meets quality standards without slowing down development.
This template is built with performance in mind, including both runtime and development-time optimizations:
- 70% faster linting on subsequent runs
- Cache persists between sessions
- Only re-lints changed files
- 95% faster type checking (~0.5s vs 10s+)
- Incremental builds track file dependencies
- Perfect for large codebases
- Conditional pre-push builds - skip builds when no source changes
- Lint-staged optimization - only check files being committed
- Cache-aware linting - leverage ESLint cache in hooks
- Fast HMR: Hot module replacement for instant feedback during development
- Tree Shaking: Automatic removal of unused code in production builds
- Code Splitting: Automatic code splitting for optimal bundle sizes
- Asset Optimization: Built-in optimization for images, fonts, and other assets
- Modern JS Output: Targets modern browsers by default for smaller bundles
- Improved Hydration: Faster initial page loads with better hydration
- Concurrent Rendering: Better user experience with non-blocking updates
- Automatic Batching: Optimized state updates for better performance
- Suspense Improvements: Enhanced loading states and error boundaries
- Intelligent Caching: Automatic background updates and cache invalidation
- Request Deduplication: Multiple components requesting same data get single request
- Stale-While-Revalidate: Instant UI updates with background data refresh
- DevTools Integration: Monitor queries, cache status, and performance
- Smaller CSS: Only includes the styles you actually use
- JIT Compilation: Styles are generated on-demand during development
- Optimized Output: Production builds contain minimal CSS
- No Build Step: CSS processing is handled automatically
# Build for production with optimizations
npm run build
# Build with bundle size analysis
npm run build:analyze
# Preview production build locally
npm run previewThe template includes tools to monitor and optimize performance:
// React Query DevTools (development only)
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
// Monitor query performance, cache hits, and data flow
<ReactQueryDevtools initialIsOpen={false} />;All performance caches are properly managed:
.eslintcache- ESLint results cache.tsbuildinfo- TypeScript incremental compilation cache- Both are git-ignored but persist locally for speed
π Performance Metrics: See PERFORMANCE.md for detailed benchmarks and optimization strategies.
This template targets modern browsers with the following support:
- Chrome: 90+
- Firefox: 88+
- Safari: 14+
- Edge: 90+
- Mobile: iOS Safari 14+, Chrome Android 90+
For legacy browser support, you can configure Vite to include polyfills:
// vite.config.ts
import { defineConfig } from 'vite';
import legacy from '@vitejs/plugin-legacy';
export default defineConfig({
plugins: [
// ... other plugins
legacy({
targets: ['defaults', 'not IE 11'],
}),
],
});# Create production build
npm run build
# The built files will be in the `dist` directory# Install Vercel CLI
npm i -g vercel
# Deploy
vercel# Install Netlify CLI
npm i -g netlify-cli
# Deploy
netlify deploy --dir=dist --prod- Build the project:
npm run build - Push the
distfolder to agh-pagesbranch - Enable GitHub Pages in repository settings
# Dockerfile
FROM node:18-alpine as builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]Create environment files for different environments:
# .env.local (development)
VITE_APP_TITLE=My App - Development
VITE_API_URL=http://localhost:3001
# .env.production (production)
VITE_APP_TITLE=My App
VITE_API_URL=https://api.myapp.comUse in your application:
const apiUrl = import.meta.env.VITE_API_URL;
const appTitle = import.meta.env.VITE_APP_TITLE;This template already implements a scalable folder structure. As your project grows, you can extend it with feature-based modules:
src/
βββ π app/ # Application configuration and setup
βββ π components/ # Reusable components organized by type
β βββ π ui/ # Basic UI components (buttons, inputs, etc.)
β βββ π layout/ # Layout components (header, footer, etc.)
β βββ ErrorBoundary.tsx # Global components
βββ π features/ # Feature-based modules
β βββ auth/ # Authentication feature
β βββ dashboard/ # Dashboard feature
β βββ profile/ # User profile feature
βββ π hooks/ # Custom React hooks
βββ π lib/ # Third-party library configurations
βββ π pages/ # Page components
βββ π styles/ # Global styles and themes
βββ π types/ # TypeScript type definitions
βββ π utils/ # Utility functions and constants
βββ main.tsx # Application entry point
Each feature in features/ follows this structure:
features/auth/
βββ components/ # Feature-specific components
βββ hooks/ # Feature-specific hooks
βββ types/ # Feature-specific types
βββ api/ # Feature-specific API calls
βββ index.ts # Feature exports
See STRUCTURE.md for detailed architecture documentation.
The following popular dependencies are already configured and ready to use:
- React Router v7 - Client-side routing with layouts
- Type definitions - Full TypeScript support
- React Query (TanStack Query) - Caching, background updates, DevTools
- Query DevTools - Development debugging interface
- React Hook Form - High-performance forms with minimal re-renders
- Zod - TypeScript-first schema validation
- Hook Form Resolvers - Seamless Zod integration
- Lucide React - Beautiful, customizable icon library (1000+ icons)
- Local Storage Hook - Persistent state management
- Performance optimizations - ESLint caching, TypeScript incremental compilation
- Smart git hooks - Conditional builds and optimized linting
# Zustand (lightweight global state)
npm install zustand
# Redux Toolkit (complex state management)
npm install @reduxjs/toolkit react-redux# Radix UI (headless components)
npm install @radix-ui/react-dialog @radix-ui/react-dropdown-menu
# shadcn/ui (pre-built components)
npx shadcn-ui@latest initThis template includes powerful storage hooks for data persistence:
For storing data in localStorage with automatic JSON serialization:
import { useLocalStorage } from '@/hooks';
const MyComponent = () => {
const [user, setUser, removeUser] = useLocalStorage('user', {
name: '',
email: '',
});
return (
<div>
<p>Welcome, {user.name}!</p>
<button
onClick={() => setUser({ name: 'John', email: '[email protected]' })}
>
Set User
</button>
<button onClick={removeUser}>Clear User</button>
</div>
);
};Features:
- Type-safe with TypeScript generics
- Automatic JSON serialization/deserialization
- Cross-tab synchronization
- Error handling for corrupted data
- SSR-safe initialization
For storing sensitive data with AES-GCM encryption:
import { useSecureStorage } from '@/hooks';
const SecureComponent = () => {
const [token, setToken, removeToken, isLoading, error] =
useSecureStorage('auth-token');
const saveToken = async () => {
await setToken('sensitive-jwt-token-here');
};
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return (
<div>
<p>Token: {token ? '***ENCRYPTED***' : 'No token'}</p>
<button onClick={saveToken}>Save Token</button>
<button onClick={removeToken}>Clear Token</button>
</div>
);
};Features:
- Web Crypto API encryption (AES-GCM with PBKDF2)
- Automatic encryption/decryption
- Configurable via environment variables
- Loading states and error handling
- Secure by default with development fallbacks
The secure storage hook uses environment variables for encryption keys:
# .env (development)
VITE_ENCRYPTION_SECRET=your-development-encryption-key
# .env.production (production)
VITE_ENCRYPTION_SECRET=your-strong-production-encryption-key-hereSecurity Best Practices:
- Use a strong, randomly generated secret in production
- Never commit production secrets to version control
- Generate keys with:
openssl rand -base64 32 - Rotate encryption keys periodically
# Framer Motion
npm install framer-motion
# React Spring
npm install @react-spring/web- Keep dependencies updated: Use
npm run upgraderegularly - Audit security: Run
npm auditto check for vulnerabilities - Bundle analysis: Monitor bundle size with Vite's built-in
--reportflag - Dependency cleanup: Remove unused dependencies with
depcheck
While not included by default, you can easily add testing:
npm install --save-dev vitest @vitest/ui jsdom
npm install --save-dev @testing-library/react @testing-library/jest-domAdd test script to package.json:
{
"scripts": {
"test": "vitest",
"test:ui": "vitest --ui",
"test:run": "vitest run"
}
}npm install --save-dev jest @types/jest
npm install --save-dev @testing-library/react @testing-library/jest-dom- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature - Make your changes
- Run tests:
npm test(if you've added testing) - Run linting:
npm run lint:fix - Format code:
npm run format - Commit changes:
git commit -m 'Add amazing feature' - Push to branch:
git push origin feature/amazing-feature - Open a Pull Request
- Use TypeScript for all new files
- Follow the existing ESLint and Prettier configurations
- Use semantic color variables from the theme system
- Write descriptive commit messages
- Add JSDoc comments for complex functions
- Keep components small and focused
# If port 5173 is in use, Vite will automatically use the next available port
# Or specify a different port:
npm run dev -- --port 3000# Clear TypeScript cache
rm -rf node_modules/.cache
npm run type-check# Fix auto-fixable issues
npm run lint:fix
# For complex issues, check the ESLint output:
npm run lint# Clear build cache
rm -rf dist
npm run build- π Documentation: Check this README and the inline code comments
- π Issues: Open an issue on GitHub for bugs or feature requests
- π¬ Discussions: Use GitHub Discussions for questions and ideas
- π§ Contact: Reach out to the maintainer for direct support
This project is licensed under the MIT License - see the LICENSE file for details.
- React Team for the amazing React 19 release with improved performance
- React Router Team for the powerful v7 routing solution
- TanStack Team for React Query - revolutionary server state management
- React Hook Form Team for the most performant form library
- Colinhacks for Zod - the best TypeScript-first validation library
- Lucide team for the beautiful, consistent icon library
- Vite Team for the lightning-fast development experience
- Tailwind CSS team for the utility-first CSS framework
- TypeScript Team for bringing static typing to JavaScript
- ESLint & Prettier teams for code quality tooling
- Open Source Community for the incredible tooling ecosystem
Special thanks to all the maintainers and contributors who make modern web development so productive and enjoyable!
Built with β€οΈ by Yousif Abozid
This template is constantly being improved. Star the repository to stay updated with the latest features and improvements!