

Also from Kynth Studios


Also from Kynth Studios


Also from Kynth Studios
1234# Code Architecture & Reusability Guidelines56## CRITICAL ARCHITECTURE RULES78### NEVER CREATE:9- Components over 300 lines10- Duplicate logic across components11- Inline API calls in UI components12- Mixed concerns (UI + business logic + API)13- Copy-pasted code blocks1415### ALWAYS CREATE:16- Single-responsibility components (20-100 lines)17- Custom hooks for reusable logic18- Service layer for API calls19- Shared types in `lib/types.ts`20- Composition patterns from smaller components2122## Component Composition Over Monoliths2324**NEVER create large, monolithic components that handle multiple concerns:**25**Avoid**: Single components or page that exceed 300 lines or handle multiple responsibilities26**Avoid**: Pages that contain all logic inline instead of using smaller components27**Avoid**: Components that mix UI rendering, business logic, and API calls2829**ALWAYS break down complex functionality into smaller, reusable pieces:**30**Create**: Focused components with single responsibilities (20-100 lines)31**Create**: Composition patterns using multiple small components32**Create**: Custom hooks for reusable logic extraction33**Create**: Separate layers for data fetching, business logic, and presentation3435## Component Organization Strategy3637### 1. Feature-Based Organization38```tsx39// Wrong: Everything in one file40const Dashboard = () => {41 // 300+ lines of mixed logic42 return <div>{/* massive JSX */}</div>43}4445// ✅ Correct: Composed from focused components46const Dashboard = () => (47 <DashboardLayout>48 <DashboardHeader />49 <DashboardStats />50 <DashboardCharts />51 <DashboardActivity />52 </DashboardLayout>53)54```5556### 2. Reusable Component Patterns57```tsx58// ✅ Base components for consistent UI patterns59const Card = ({ children, className, ...props }) => (60 <div className={cn("rounded-lg border bg-card", className)} {...props}>61 {children}62 </div>63)6465// ✅ Composite components for complex patterns66const StatsCard = ({ title, value, change, icon: Icon }) => (67 <Card className="p-6">68 <div className="flex items-center justify-between">69 <div>70 <p className="text-sm text-muted-foreground">{title}</p>71 <p className="text-2xl font-bold">{value}</p>72 <p className="text-sm text-green-600">{change}</p>73 </div>74 <Icon className="h-8 w-8 text-muted-foreground" />75 </div>76 </Card>77)78```7980### 3. Logic Extraction Patterns81```tsx82// ✅ Custom hooks for reusable stateful logic83const useLocalStorage = (key: string, initialValue: any) => {84 const [storedValue, setStoredValue] = useState(() => {85 try {86 const item = window.localStorage.getItem(key)87 return item ? JSON.parse(item) : initialValue88 } catch (error) {89 return initialValue90 }91 })9293 const setValue = (value: any) => {94 try {95 setStoredValue(value)96 window.localStorage.setItem(key, JSON.stringify(value))97 } catch (error) {98 console.error(error)99 }100 }101102 return [storedValue, setValue]103}104105// ✅ Service layer for API interactions106export const userService = {107 async getUser(id: string) {108 const response = await fetch(`/api/users/${id}`)109 return response.json()110 },111112 async updateUser(id: string, data: Partial<User>) {113 const response = await fetch(`/api/users/${id}`, {114 method: 'PATCH',115 headers: { 'Content-Type': 'application/json' },116 body: JSON.stringify(data)117 })118 return response.json()119 }120}121```122123## File Organization Best Practices124125### 1. Component File Structure126```tsx127// ComponentName/index.ts - Export barrel128export { ComponentName } from './ComponentName'129export type { ComponentNameProps } from './ComponentName'130131// ComponentName/ComponentName.tsx - Main component132interface ComponentNameProps {133 // Props definition134}135136export const ComponentName = ({ ...props }: ComponentNameProps) => {137 // Component implementation138}139140// ComponentName/ComponentName.stories.tsx - Storybook stories (if used)141// ComponentName/ComponentName.test.tsx - Tests (if used)142```143144### 2. Shared Type Definitions145```tsx146// lib/types.ts - Shared application types147export interface User {148 id: string149 email: string150 name: string151 avatar?: string152}153154export interface ApiResponse<T> {155 data: T156 message: string157 success: boolean158}159160export type Theme = 'light' | 'dark' | 'system'161export type UserRole = 'admin' | 'user' | 'guest'162```163164### 3. Utility Function Organization165```tsx166// lib/utils.ts - General utilities (keep existing cn function)167export function cn(...inputs: ClassValue[]) {168 return twMerge(clsx(inputs))169}170171export function formatDate(date: Date | string, format?: string): string {172 // Date formatting utility173}174175export function debounce<T extends (...args: any[]) => any>(176 func: T,177 wait: number178): (...args: Parameters<T>) => void {179 // Debounce utility180}181182// lib/constants.ts - Application constants183export const API_ENDPOINTS = {184 USERS: '/api/users',185 POSTS: '/api/posts',186 AUTH: '/api/auth'187} as const188189export const QUERY_KEYS = {190 USERS: 'users',191 POSTS: 'posts',192 USER_PROFILE: 'user-profile'193} as const194```195196## Custom Hook Patterns for Reusability197198### 1. Data Fetching Hooks199```tsx200// hooks/useUsers.ts201export const useUsers = () => {202 return useQuery({203 queryKey: [QUERY_KEYS.USERS],204 queryFn: () => userService.getAllUsers()205 })206}207208export const useUser = (id: string) => {209 return useQuery({210 queryKey: [QUERY_KEYS.USERS, id],211 queryFn: () => userService.getUser(id),212 enabled: !!id213 })214}215```216217### 2. Form Handling Hooks218```tsx219// hooks/useUserForm.ts220export const useUserForm = (initialData?: Partial<User>) => {221 const form = useForm<UserFormData>({222 resolver: zodResolver(userSchema),223 defaultValues: {224 name: initialData?.name || '',225 email: initialData?.email || '',226 // ... other fields227 }228 })229230 const { mutate: saveUser, isPending } = useMutation({231 mutationFn: userService.updateUser,232 onSuccess: () => {233 toast.success('User updated successfully')234 }235 })236237 return { form, saveUser, isPending }238}239```240241### 3. UI State Hooks242```tsx243// hooks/useDisclosure.ts244export const useDisclosure = (initialState = false) => {245 const [isOpen, setIsOpen] = useState(initialState)246247 const open = useCallback(() => setIsOpen(true), [])248 const close = useCallback(() => setIsOpen(false), [])249 const toggle = useCallback(() => setIsOpen(prev => !prev), [])250251 return { isOpen, open, close, toggle }252}253```254255## Validation Schema Reusability256257### 1. Shared Zod Schemas258```tsx259// lib/validations/common.ts260export const emailSchema = z.string().email('Invalid email address')261export const phoneSchema = z.string().regex(/^\+?[\d\s-()]+$/, 'Invalid phone number')262263// lib/validations/user.ts264export const userSchema = z.object({265 name: z.string().min(2, 'Name must be at least 2 characters'),266 email: emailSchema,267 phone: phoneSchema.optional(),268 role: z.enum(['admin', 'user', 'guest'])269})270271export type UserFormData = z.infer<typeof userSchema>272```273274## Component Composition Patterns275276### 1. Compound Components277```tsx278// components/common/DataTable/DataTable.tsx279const DataTable = ({ children }: { children: React.ReactNode }) => (280 <div className="border rounded-lg overflow-hidden">281 {children}282 </div>283)284285const DataTableHeader = ({ children }: { children: React.ReactNode }) => (286 <div className="bg-muted p-4 border-b">287 {children}288 </div>289)290291const DataTableBody = ({ children }: { children: React.ReactNode }) => (292 <div className="divide-y">293 {children}294 </div>295)296297// Usage: Flexible composition298<DataTable>299 <DataTableHeader>300 <h3>Users</h3>301 </DataTableHeader>302 <DataTableBody>303 {users.map(user => <UserRow key={user.id} user={user} />)}304 </DataTableBody>305</DataTable>306```307308### 2. Render Props Pattern309```tsx310// components/common/DataLoader.tsx311interface DataLoaderProps<T> {312 data: T[] | undefined313 isLoading: boolean314 error: Error | null315 children: (data: T[]) => React.ReactNode316 loadingComponent?: React.ReactNode317 errorComponent?: (error: Error) => React.ReactNode318 emptyComponent?: React.ReactNode319}320321export const DataLoader = <T,>({322 data,323 isLoading,324 error,325 children,326 loadingComponent = <div>Loading...</div>,327 errorComponent = (err) => <div>Error: {err.message}</div>,328 emptyComponent = <div>No data found</div>329}: DataLoaderProps<T>) => {330 if (isLoading) return <>{loadingComponent}</>331 if (error) return <>{errorComponent(error)}</>332 if (!data || data.length === 0) return <>{emptyComponent}</>333 return <>{children(data)}</>334}335```336337## CRITICAL RULES FOR CODE ORGANIZATION3383391. **Single Responsibility**: Each component should have one clear purpose3402. **Composition Over Inheritance**: Build complex UIs by combining simple components3413. **Extract Logic**: Move reusable logic into custom hooks, not copy-paste3424. **Shared Types**: Define interfaces once, import everywhere3435. **Service Layer**: Keep API calls separate from UI components3446. **Consistent Patterns**: Use the same patterns across the entire application3457. **Import Organization**: Group imports by type (React, libraries, local)346347## Project Structure348```349/350├── src/351│ ├── components/352│ │ ├── ui/ # shadcn/ui components (pre-built)353│ │ ├── common/ # Reusable components (Header, Footer, Layout)354│ │ ├── forms/ # Form-specific components355│ │ └── features/ # Feature-specific component groups356│ ├── hooks/ # Custom React hooks (reusable logic)357│ ├── integrations/358│ │ └── supabase/ # Supabase client configuration359│ │ ├── client.ts # Supabase client instance360│ │ └── types.ts # Auto-generated database types361│ ├── lib/362│ │ ├── utils.ts # General utility functions363│ │ ├── constants.ts # App constants and enums364│ │ ├── types.ts # Shared TypeScript types365│ │ └── validations/ # Zod schemas and form validations366│ ├── pages/ # Route components (composition only)367│ ├── services/ # API calls and external service integrations368│ ├── context/ # React context providers369│ ├── App.tsx # Main app component with routing370│ ├── main.tsx # Entry point371│ └── index.css # Global styles372├── supabase/ # Supabase local development373│ ├── config.toml # Supabase CLI configuration374│ └── migrations/ # Database migrations (auto-generated)375├── public/ # Static assets376├── package.json # Dependencies and scripts377├── vite.config.ts # Vite configuration (@ → ./src, port 8080)378├── tailwind.config.ts # Tailwind configuration (dark mode support)379├── components.json # shadcn/ui configuration380└── tsconfig.json # TypeScript configuration381```
One repository carrying more than one format is the comparison this product exists for: does anyone actually write different content in each file, or is one a copy of the other?
| Repository | Format | Stack | Covers | Score | Changed |
|---|---|---|---|---|---|
| chihebnabil/lovable-boilerplate.cursor/rules/core.mdc · 65 | Cursor rules | buildlint-formatarchui+1 | 92/100 | 14 days ago | |
| chihebnabil/lovable-boilerplate.cursor/rules/forms.mdc · 65 | Cursor rules | setupstyledo-not | 73/100 | 14 days ago | |
| chihebnabil/lovable-boilerplate.cursor/rules/hooks.mdc · 65 | Cursor rules | styleuido-not | 61/100 | 14 days ago | |
| chihebnabil/lovable-boilerplate.cursor/rules/quality.mdc · 65 | Cursor rules | buildlint-formatstyleui+3 | 88/100 | 14 days ago | |
| chihebnabil/lovable-boilerplate.cursor/rules/services.mdc · 65 | Cursor rules | archtypesdo-not | 73/100 | 14 days ago | |
| chihebnabil/lovable-boilerplate.cursor/rules/typescript.mdc · 65 | Cursor rules | setupstyletypessecurity+2 | 73/100 | 14 days ago | |
| chihebnabil/lovable-boilerplate.github/instructions/components.instructions.md · 65 | Copilot instructions | styleuido-not | 61/100 | 14 days ago | |
| chihebnabil/lovable-boilerplate.github/instructions/design.instructions.md · 65 | Copilot instructions | lint-formatstyleuido-not | 61/100 | 14 days ago | |
| chihebnabil/lovable-boilerplate.github/instructions/development.instructions.md · 65 | Copilot instructions | setupbuildtestlint-format+7 | 88/100 | 14 days ago | |
| chihebnabil/lovable-boilerplate.github/instructions/global.instructions.md · 65 | Copilot instructions | buildlint-formatstylearch+4 | 100/100 | 14 days ago | |
| chihebnabil/lovable-boilerplate.github/instructions/hooks.instructions.md · 65 | Copilot instructions | styleui | 54/100 | 14 days ago | |
| chihebnabil/lovable-boilerplate.github/instructions/lib.instructions.md · 65 | Copilot instructions | archtypesdo-not | 69/100 | 14 days ago | |
| chihebnabil/lovable-boilerplate.github/instructions/pages.instructions.md · 65 | Copilot instructions | archuido-not | 69/100 | 14 days ago | |
| chihebnabil/lovable-boilerplate.github/instructions/quality.instructions.md · 65 | Copilot instructions | lint-formatdeploymentdo-not | 63/100 | 14 days ago | |
| chihebnabil/lovable-boilerplate.github/instructions/reusable.instructions.md · 65 | Copilot instructions | uido-notagent-behaviour | 32/100 | 14 days ago | |
| chihebnabil/lovable-boilerplate.cursor/rules/components.mdc · 65 | Cursor rules | stylearchuido-not | 65/100 | 14 days ago | |
| chihebnabil/lovable-boilerplate.cursor/rules/design.mdc · 65 | Cursor rules | styleuido-not | 65/100 | 14 days ago | |
| chihebnabil/lovable-boilerplateCLAUDE.md · 65 | CLAUDE.md | setupbuildtestlint-format+5 | 89/100 | 14 days ago |
Same format, overlapping stack, ranked by quality.
| Repository | Format | Stack | Covers | Score | Changed |
|---|---|---|---|---|---|
| chihebnabil/lovable-boilerplate.github/instructions/global.instructions.md · 65 | Copilot instructions | buildlint-formatstylearch+4 | 100/100 | 14 days ago | |
| louislam/uptime-kuma.github/copilot-instructions.md · 90k | Copilot instructions | setupbuildtestlint-format+9 | 100/100 | 14 days ago | |
| JCodesMore/ai-website-cloner-template.github/copilot-instructions.md · 32k | Copilot instructions | buildlint-formatstylearch+3 | 97/100 | 7 days ago | |
| bagisto/bagisto.github/copilot-instructions.md · 28k | Copilot instructions | setupbuildteststyle+5 | 97/100 | 14 days ago | |
| darkmatter/nixmac.github/copilot-instructions.md · 25 | Copilot instructions | setupbuildtestlint-format+8 | 96/100 | 14 days ago | |
| nerolis-lab/nerolis-lab.github/copilot-instructions.md · 32 | Copilot instructions | setupbuildtestlint-format+11 | 96/100 | 14 days ago | |
| thangaram611/second-brain.github/copilot-instructions.md · 0 | Copilot instructions | setupteststylearch+4 | 96/100 | 14 days ago | |
| doubts-suplab/eeik-bootstrap.github/instructions/cdk-terraform.instructions.md · 1 | Copilot instructions | teststylearchtypes+2 | 96/100 | today |
A badge carrying the measured quality of the strongest agent config file in this repository, out of 100. It reads from this index every time somebody loads your page, so it changes when the measurement changes and there is nothing to keep up to date. Free, no account, and the value is not something you or we can set by hand.
[](https://rulestack.kynth.studio/configs/chihebnabil-lovable-boilerplate-github-instructions-architecture-instructions)Would rather not hotlink us? Every badge is also served in shields.io’s endpoint schema, so shields renders the image and your readers never talk to our domain:
Published by Toolproof, the masthead over this index and eight others. The method behind the number is at toolproof.kynth.studio/methodology, and the whole thing is readable as JSON with no key at /api.