React Rules(3)
A custom hook for managing form state in React
function useForm<T>(initialState: T) {
const [values, setValues] = useState<T>(initialState)
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const { name, value } = e.target
setValues(prev => ({ ...prev, [name]: value }))
}
const resetForm = () => setValues(initialState)
return { values, handleChange, resetForm }
}
react
A reusable error boundary component for handling React errors gracefully
class ErrorBoundary extends React.Component<
{ children: React.ReactNode },
{ hasError: boolean }
> {
constructor(props) {
super(props)
this.state = { hasError: false }
}
static getDerivedStateFromError(error) {
return { hasError: true }
}
componentDidCatch(error, errorInfo) {
console.error('Error caught by boundary:', error, errorInfo)
}
render() {
if (this.state.hasError) {
return <div>Something went wrong. Please try again.</div>
}
return this.props.children
}
}
react
A pattern for creating flexible and composable components in React
import { createContext, useContext, ReactNode } from 'react'
interface TabsContext {
activeTab: string
setActiveTab: (id: string) => void
}
const TabsContext = createContext<TabsContext | null>(null)
function Tabs({ children }: { children: ReactNode }) {
const [activeTab, setActiveTab] = useState('')
return (
<TabsContext.Provider value={{ activeTab, setActiveTab }}>
{children}
</TabsContext.Provider>
)
}
function TabList({ children }: { children: ReactNode }) {
return <div role="tablist">{children}</div>
}
function Tab({ id, children }: { id: string; children: ReactNode }) {
const context = useContext(TabsContext)
if (!context) throw new Error('Tab must be used within Tabs')
const { activeTab, setActiveTab } = context
return (
<button
role="tab"
aria-selected={activeTab === id}
onClick={() => setActiveTab(id)}
>
{children}
</button>
)
}
function TabPanel({ id, children }: { id: string; children: ReactNode }) {
const context = useContext(TabsContext)
if (!context) throw new Error('TabPanel must be used within Tabs')
return context.activeTab === id ? <div>{children}</div> : null
}
// Usage
<Tabs>
<TabList>
<Tab id="tab1">Tab 1</Tab>
<Tab id="tab2">Tab 2</Tab>
</TabList>
<TabPanel id="tab1">Content 1</TabPanel>
<TabPanel id="tab2">Content 2</TabPanel>
</Tabs>
react
TypeScript Rules(2)
A reusable interface for handling API responses in TypeScript
interface ApiResponse<T> {
data: T;
status: number;
message: string;
success: boolean;
timestamp: string;
pagination?: {
page: number;
limit: number;
total: number;
hasMore: boolean;
};
meta?: Record<string, unknown>;
}
// Example usage with a User type
interface User {
id: string;
name: string;
email: string;
role: 'admin' | 'user';
}
// Using the ApiResponse with User type
type UserApiResponse = ApiResponse<User>;
typescript
Essential utility types for TypeScript development
// Make all properties optional
type Partial<T> = {
[P in keyof T]?: T[P];
};
// Make all properties required
type Required<T> = {
[P in keyof T]-?: T[P];
};
// Make all properties readonly
type Readonly<T> = {
readonly [P in keyof T]: T[P];
};
// Pick specific properties
type Pick<T, K extends keyof T> = {
[P in K]: T[P];
};
// Omit specific properties
type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;
typescript
Next.js Rules(2)
Using Server Actions in Next.js 14 for form submissions
'use server'
async function createPost(formData: FormData) {
const title = formData.get('title')
const content = formData.get('content')
await db.post.create({
data: { title, content }
})
revalidatePath('/posts')
}
export default function PostForm() {
return (
<form action={createPost}>
<input name="title" />
<textarea name="content" />
<button type="submit">Create Post</button>
</form>
)
}
nextjs
Implementing parallel routes in Next.js 14 for complex layouts
// app/@modal/page.tsx
export default function Modal() {
return (
<div className="modal">
<h1>I'm rendered in parallel!</h1>
</div>
)
}
// app/layout.tsx
export default function Layout({
children,
modal
}: {
children: React.ReactNode
modal: React.ReactNode
}) {
return (
<div>
{children}
{modal}
</div>
)
}
nextjs
Python Rules(2)
Learn how to use decorators in Python
# Function decorator
def timing_decorator(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"{func.__name__} took {end_time - start_time:.2f} seconds")
return result
return wrapper
@timing_decorator
def slow_function():
time.sleep(1)
print("Function finished!")
# Class decorator
def singleton(cls):
instances = {}
def get_instance(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return get_instance
@singleton
class DatabaseConnection:
def __init__(self):
print("Initializing database connection...")
python
Using type hints in Python for better code quality
from typing import List, Dict, Optional
def process_items(items: List[str]) -> Dict[str, int]:
return {item: len(item) for item in items}
def find_user(user_id: int) -> Optional[Dict[str, str]]:
# Simulating database lookup
users = {
1: {"name": "John", "email": "john@example.com"},
2: {"name": "Jane", "email": "jane@example.com"}
}
return users.get(user_id)
# Example usage
items = ["apple", "banana", "cherry"]
result = process_items(items)
print(result) # {'apple': 5, 'banana': 6, 'cherry': 6}
user = find_user(1)
if user:
print(f"Found user: {user['name']}")
python
PHP Rules(1)
Implementing PSR-4 compliant class autoloader in PHP
<?php
spl_autoload_register(function ($class) {
$prefix = 'App\\';
$base_dir = __DIR__ . '/src/';
$len = strlen($prefix);
if (strncmp($prefix, $class, $len) !== 0) {
return;
}
$relative_class = substr($class, $len);
$file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';
if (file_exists($file)) {
require $file;
}
});
php