Code Examples
Complete working examples for common use cases.
Table of Contents
- Forms
- Data Fetching
- Modals
- Notifications
- Search
- Internationalization
- State Management
- Error Handling
- Performance
Forms
Basic Form
'use client';
import { useForm } from '@/hooks/useForm';
import { useState } from 'react';
export default function ContactForm() {
const { values, handleChange, handleSubmit, errors, isSubmitting } = useForm({
initialValues: {
name: '',
email: '',
message: '',
},
validation: {
name: { required: true, minLength: 2 },
email: { required: true, email: true },
message: { required: true, minLength: 10 },
},
onSubmit: async (values) => {
const response = await fetch('/api/contact', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(values),
});
if (response.ok) {
alert('Message sent!');
}
},
});
return (
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label htmlFor="name">Name</label>
<input
id="name"
name="name"
value={values.name}
onChange={handleChange}
className="w-full p-2 border rounded"
/>
{errors.name && <span className="text-red-500">{errors.name}</span>}
</div>
<div>
<label htmlFor="email">Email</label>
<input
id="email"
type="email"
name="email"
value={values.email}
onChange={handleChange}
className="w-full p-2 border rounded"
/>
{errors.email && <span className="text-red-500">{errors.email}</span>}
</div>
<div>
<label htmlFor="message">Message</label>
<textarea
id="message"
name="message"
value={values.message}
onChange={handleChange}
className="w-full p-2 border rounded"
rows={5}
/>
{errors.message && <span className="text-red-500">{errors.message}</span>}
</div>
<button
type="submit"
disabled={isSubmitting}
className="px-4 py-2 bg-blue-500 text-white rounded disabled:opacity-50"
>
{isSubmitting ? 'Sending...' : 'Send Message'}
</button>
</form>
);
}
Multi-Step Form
'use client';
import MultiStepForm from '@/components/MultiStepForm';
import { useForm } from '@/hooks/useForm';
export default function RegistrationForm() {
const step1Form = useForm({
initialValues: { firstName: '', lastName: '' },
onSubmit: async () => {},
});
const step2Form = useForm({
initialValues: { email: '', password: '' },
onSubmit: async () => {},
});
return (
<MultiStepForm
steps={[
{
id: '1',
title: 'Personal Information',
component: (
<div>
<input
name="firstName"
value={step1Form.values.firstName}
onChange={step1Form.handleChange}
placeholder="First Name"
/>
<input
name="lastName"
value={step1Form.values.lastName}
onChange={step1Form.handleChange}
placeholder="Last Name"
/>
</div>
),
},
{
id: '2',
title: 'Account Details',
component: (
<div>
<input
name="email"
type="email"
value={step2Form.values.email}
onChange={step2Form.handleChange}
placeholder="Email"
/>
<input
name="password"
type="password"
value={step2Form.values.password}
onChange={step2Form.handleChange}
placeholder="Password"
/>
</div>
),
},
]}
initialValues={{}}
onSubmit={async (values) => {
console.log('Final submission:', values);
}}
/>
);
}
Data Fetching
Basic Data Fetching
'use client';
import { useDataFetch } from '@/hooks/useDataFetch';
import { LoadingState } from '@/components/LoadingStates';
export default function UserList() {
const { data, isLoading, error, refetch } = useDataFetch('/api/users', {
cache: { strategy: 'cache-first', ttl: 60000 },
});
if (isLoading) return <LoadingState />;
if (error) return <div>Error: {error.message}</div>;
return (
<div>
<button onClick={refetch}>Refresh</button>
<ul>
{data?.map((user: any) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
</div>
);
}
Data Fetching with Retry
'use client';
import { useDataFetch } from '@/hooks/useDataFetch';
import { useRetry } from '@/hooks/useRetry';
export default function DataComponent() {
const fetchData = async () => {
const response = await fetch('/api/data');
if (!response.ok) throw new Error('Failed');
return response.json();
};
const { retry, isRetrying } = useRetry(fetchData, {
maxRetries: 3,
delay: 1000,
});
return (
<div>
<button onClick={retry} disabled={isRetrying}>
{isRetrying ? 'Retrying...' : 'Fetch Data'}
</button>
</div>
);
}
Modals
Basic Modal
'use client';
import { useState } from 'react';
import Modal from '@/components/Modal';
export default function ModalExample() {
const [isOpen, setIsOpen] = useState(false);
return (
<>
<button onClick={() => setIsOpen(true)}>Open Modal</button>
<Modal
isOpen={isOpen}
onClose={() => setIsOpen(false)}
title="Example Modal"
size="md"
>
<p>This is modal content.</p>
<button onClick={() => setIsOpen(false)}>Close</button>
</Modal>
</>
);
}
Confirmation Modal
'use client';
import { useState } from 'react';
import Modal from '@/components/Modal';
export default function DeleteConfirmation({ onConfirm }: { onConfirm: () => void }) {
const [isOpen, setIsOpen] = useState(false);
return (
<>
<button onClick={() => setIsOpen(true)}>Delete</button>
<Modal
isOpen={isOpen}
onClose={() => setIsOpen(false)}
title="Confirm Delete"
size="sm"
>
<p>Are you sure you want to delete this item?</p>
<div className="flex gap-2 mt-4">
<button
onClick={() => {
onConfirm();
setIsOpen(false);
}}
className="px-4 py-2 bg-red-500 text-white rounded"
>
Delete
</button>
<button
onClick={() => setIsOpen(false)}
className="px-4 py-2 bg-gray-500 text-white rounded"
>
Cancel
</button>
</div>
</Modal>
</>
);
}
Notifications
Success Notification
'use client';
import { notifications } from '@/lib/notifications';
export default function SaveButton() {
const handleSave = async () => {
try {
await saveData();
notifications.success('Saved!', 'Your changes have been saved successfully');
} catch (error) {
notifications.error('Error', 'Failed to save changes');
}
};
return <button onClick={handleSave}>Save</button>;
}
Notification with Action
'use client';
import { notifications } from '@/lib/notifications';
export default function UndoExample() {
const handleAction = () => {
notifications.show({
type: 'success',
title: 'Item deleted',
message: 'The item has been deleted',
duration: 5000,
action: {
label: 'Undo',
onClick: () => {
// Undo action
notifications.info('Undone', 'Item restored');
},
},
});
};
return <button onClick={handleAction}>Delete Item</button>;
}
Search
Basic Search
'use client';
import { useState } from 'react';
import { searchApps } from '@/lib/search';
import { useDebounce } from '@/hooks/useDebounce';
export default function SearchComponent({ apps }: { apps: any[] }) {
const [query, setQuery] = useState('');
const debouncedQuery = useDebounce(query, 300);
const [results, setResults] = useState<any[]>([]);
useEffect(() => {
if (debouncedQuery) {
const searchResults = searchApps(apps, debouncedQuery, {
threshold: 0.3,
limit: 50,
fuzzy: true,
});
setResults(searchResults.map(r => r.app));
} else {
setResults([]);
}
}, [debouncedQuery, apps]);
return (
<div>
<input
type="search"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Search..."
className="w-full p-2 border rounded"
/>
<ul>
{results.map((app) => (
<li key={app.id}>{app.title}</li>
))}
</ul>
</div>
);
}
Advanced Search with Filters
'use client';
import { useState } from 'react';
import { advancedSearch } from '@/lib/advanced-search';
export default function AdvancedSearch({ apps }: { apps: any[] }) {
const [query, setQuery] = useState('');
const [minRating, setMinRating] = useState(0);
const [selectedTags, setSelectedTags] = useState<string[]>([]);
const results = advancedSearch(apps, {
query,
filters: {
minRating,
tags: selectedTags,
},
sortBy: 'rating',
limit: 20,
});
return (
<div>
<input
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Search..."
/>
<input
type="number"
value={minRating}
onChange={(e) => setMinRating(Number(e.target.value))}
placeholder="Min Rating"
min="0"
max="5"
/>
<div>
{results.map((result) => (
<div key={result.app.id}>{result.app.title}</div>
))}
</div>
</div>
);
}
Internationalization
Basic i18n
'use client';
import { useI18n } from '@/hooks/useI18n';
import LanguageSelector from '@/components/LanguageSelector';
export default function LocalizedComponent() {
const { t, locale } = useI18n();
return (
<div>
<LanguageSelector />
<h1>{t('common.loading')}</h1>
<p>Current locale: {locale}</p>
</div>
);
}
Dynamic Translations
'use client';
import { useI18n } from '@/hooks/useI18n';
export default function WelcomeMessage({ userName }: { userName: string }) {
const { t } = useI18n();
return (
<div>
<h1>{t('welcome.message', { name: userName })}</h1>
</div>
);
}
State Management
Persisted State
'use client';
import { usePersistedState } from '@/hooks/usePersistedState';
export default function SettingsComponent() {
const [settings, setSettings] = usePersistedState('settings', {
theme: 'light',
language: 'en',
});
return (
<div>
<select
value={settings.theme}
onChange={(e) =>
setSettings({ ...settings, theme: e.target.value })
}
>
<option value="light">Light</option>
<option value="dark">Dark</option>
</select>
</div>
);
}
Global State Store
'use client';
import { createStore } from '@/lib/state-management';
import { useStore } from '@/hooks/useStore';
const userStore = createStore({ name: '', email: '' });
export default function UserProfile() {
const [user, setUser] = useStore(userStore);
return (
<div>
<input
value={user.name}
onChange={(e) => setUser({ ...user, name: e.target.value })}
placeholder="Name"
/>
<input
value={user.email}
onChange={(e) => setUser({ ...user, email: e.target.value })}
placeholder="Email"
/>
</div>
);
}
Error Handling
Error Boundary
import { ErrorBoundaryAdvanced } from '@/components/ErrorBoundaryAdvanced';
export default function App() {
return (
<ErrorBoundaryAdvanced
onError={(error, errorInfo) => {
console.error('Error caught:', error, errorInfo);
}}
>
<YourApp />
</ErrorBoundaryAdvanced>
);
}
Error Recovery
'use client';
import ErrorRecovery from '@/components/ErrorRecovery';
import { useState } from 'react';
export default function ErrorComponent() {
const [error, setError] = useState<Error | null>(null);
const handleError = () => {
try {
// Code that might throw
throw new Error('Something went wrong');
} catch (e) {
setError(e as Error);
}
};
return (
<div>
<button onClick={handleError}>Trigger Error</button>
{error && (
<ErrorRecovery
error={error}
onRecover={() => setError(null)}
/>
)}
</div>
);
}
Performance
Lazy Loading
import dynamic from 'next/dynamic';
import { LoadingState } from '@/components/LoadingStates';
const HeavyComponent = dynamic(() => import('./HeavyComponent'), {
loading: () => <LoadingState />,
ssr: false,
});
export default function Page() {
return (
<div>
<HeavyComponent />
</div>
);
}
Image Optimization
import Image from 'next/image';
export default function OptimizedImage() {
return (
<Image
src="/image.jpg"
width={800}
height={600}
alt="Description"
loading="lazy"
placeholder="blur"
/>
);
}
Virtual Scrolling
'use client';
import { VirtualList } from '@/components/VirtualList';
export default function LargeList({ items }: { items: any[] }) {
return (
<VirtualList
items={items}
itemHeight={50}
renderItem={(item) => (
<div className="p-4 border-b">
{item.name}
</div>
)}
/>
);
}
More Examples
For more examples, see:
- Guides - Step-by-step guides
- API Documentation - API examples
- Components - Component examples