useAuth
Manages user authentication state and provides authentication methods.
Parameters
Configuration options for the authentication hook
Automatically refresh tokens when they expire
URL to redirect to after logout
Return Value
The currently authenticated user object, or null if not authenticated
Whether a user is currently authenticated
Whether authentication state is being loaded
login
(credentials: LoginCredentials) => Promise<void>
Function to log in a user with email and password
Function to log out the current user
register
(data: RegisterData) => Promise<void>
Function to register a new user
Example
import { useAuth } from '@/hooks/useAuth';
function ProfilePage() {
const { user, isAuthenticated, logout } = useAuth();
if (!isAuthenticated) {
return <div>Please log in</div>;
}
return (
<div>
<h1>Welcome, {user.name}</h1>
<button onClick={logout}>Logout</button>
</div>
);
}
Manages form state, validation, and submission with TypeScript support.
Parameters
Initial form values object
Form configuration options
validate
(values: T) => ValidationErrors<T>
Validation function that returns error messages
onSubmit
(values: T) => Promise<void> | void
Form submission handler
Run validation on every field change
Run validation when field loses focus
Return Value
Validation errors for each field
Which fields have been interacted with
Whether form is currently being submitted
handleChange
(field: keyof T, value: any) => void
Update a field value
handleSubmit
(e?: React.FormEvent) => Promise<void>
Submit the form
Reset form to initial values
setFieldValue
(field: keyof T, value: any) => void
Programmatically set a field value
Example
import { useForm } from '@/hooks/useForm';
interface ContactForm {
name: string;
email: string;
message: string;
}
function ContactPage() {
const { values, errors, touched, handleChange, handleSubmit } = useForm<ContactForm>({
name: '',
email: '',
message: ''
}, {
validate: (values) => {
const errors: any = {};
if (!values.email.includes('@')) {
errors.email = 'Invalid email';
}
if (values.message.length < 10) {
errors.message = 'Message too short';
}
return errors;
},
onSubmit: async (values) => {
await fetch('/api/contact', {
method: 'POST',
body: JSON.stringify(values)
});
}
});
return (
<form onSubmit={handleSubmit}>
<input
value={values.name}
onChange={(e) => handleChange('name', e.target.value)}
/>
{touched.name && errors.name && <span>{errors.name}</span>}
{/* other fields */}
</form>
);
}
useFetch
Data fetching hook with loading, error states, and caching support.
Parameters
The URL to fetch data from
Fetch configuration options
method
'GET' | 'POST' | 'PUT' | 'DELETE'
default:"'GET'"
HTTP method to use
Additional headers to send
Whether to automatically fetch on mount
Interval in milliseconds to refetch data
Callback when fetch succeeds
Callback when fetch fails
Return Value
Error object if the fetch failed
Whether data is currently being fetched
Whether data is being revalidated in the background
Manually trigger a refetch
Manually update the cached data
Example
import { useFetch } from '@/hooks/useFetch';
interface User {
id: number;
name: string;
email: string;
}
function UserProfile({ userId }: { userId: number }) {
const { data, error, isLoading } = useFetch<User>(
`/api/users/${userId}`
);
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
if (!data) return null;
return (
<div>
<h1>{data.name}</h1>
<p>{data.email}</p>
</div>
);
}
useLocalStorage
Persists state to localStorage with automatic synchronization across tabs.
Parameters
The localStorage key to store the value under
Initial value if no stored value exists
Storage configuration options
serializer
(value: T) => string
default:"JSON.stringify"
Custom serialization function
deserializer
(value: string) => T
default:"JSON.parse"
Custom deserialization function
Sync changes across browser tabs
Return Value
setValue
(value: T | ((prev: T) => T)) => void
Update the stored value
Remove the value from localStorage
Example
import { useLocalStorage } from '@/hooks/useLocalStorage';
function ThemeToggle() {
const [theme, setTheme] = useLocalStorage<'light' | 'dark'>(
'theme',
'light'
);
const toggleTheme = () => {
setTheme(current => current === 'light' ? 'dark' : 'light');
};
return (
<button onClick={toggleTheme}>
Current theme: {theme}
</button>
);
}
useDebounce
Debounces a value, useful for search inputs and performance optimization.
Parameters
Delay in milliseconds before updating the debounced value
Return Value
The debounced value that updates after the specified delay
Example
import { useDebounce } from '@/hooks/useDebounce';
import { useFetch } from '@/hooks/useFetch';
function SearchUsers() {
const [searchTerm, setSearchTerm] = useState('');
const debouncedSearch = useDebounce(searchTerm, 500);
const { data, isLoading } = useFetch(
`/api/users/search?q=${debouncedSearch}`,
{ enabled: debouncedSearch.length > 0 }
);
return (
<div>
<input
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
placeholder="Search users..."
/>
{isLoading && <span>Searching...</span>}
{/* render results */}
</div>
);
}
Responds to CSS media query changes for responsive design.
Parameters
CSS media query string (e.g., ‘(min-width: 768px)‘)
Return Value
Whether the media query currently matches
Example
import { useMediaQuery } from '@/hooks/useMediaQuery';
function ResponsiveLayout() {
const isMobile = useMediaQuery('(max-width: 768px)');
const isTablet = useMediaQuery('(min-width: 769px) and (max-width: 1024px)');
const isDesktop = useMediaQuery('(min-width: 1025px)');
return (
<div>
{isMobile && <MobileNav />}
{isTablet && <TabletNav />}
{isDesktop && <DesktopNav />}
</div>
);
}