Skip to main content

useAuth

Manages user authentication state and provides authentication methods.

Parameters

options
UseAuthOptions
Configuration options for the authentication hook

Return Value

user
User | null
The currently authenticated user object, or null if not authenticated
isAuthenticated
boolean
Whether a user is currently authenticated
isLoading
boolean
Whether authentication state is being loaded
login
(credentials: LoginCredentials) => Promise<void>
Function to log in a user with email and password
logout
() => Promise<void>
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>
  );
}

useForm

Manages form state, validation, and submission with TypeScript support.

Parameters

initialValues
T
required
Initial form values object
options
UseFormOptions<T>
Form configuration options

Return Value

values
T
Current form values
errors
ValidationErrors<T>
Validation errors for each field
touched
Record<keyof T, boolean>
Which fields have been interacted with
isSubmitting
boolean
Whether form is currently being submitted
handleChange
(field: keyof T, value: any) => void
Update a field value
handleBlur
(field: keyof T) => void
Mark a field as touched
handleSubmit
(e?: React.FormEvent) => Promise<void>
Submit the form
resetForm
() => void
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

url
string
required
The URL to fetch data from
options
UseFetchOptions<T>
Fetch configuration options

Return Value

data
T | null
The fetched data
error
Error | null
Error object if the fetch failed
isLoading
boolean
Whether data is currently being fetched
isValidating
boolean
Whether data is being revalidated in the background
refetch
() => Promise<void>
Manually trigger a refetch
mutate
(data: T) => void
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

key
string
required
The localStorage key to store the value under
initialValue
T
required
Initial value if no stored value exists
options
UseLocalStorageOptions
Storage configuration options

Return Value

value
T
The current stored value
setValue
(value: T | ((prev: T) => T)) => void
Update the stored value
removeValue
() => void
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

value
T
required
The value to debounce
delay
number
required
Delay in milliseconds before updating the debounced value

Return Value

debouncedValue
T
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>
  );
}

useMediaQuery

Responds to CSS media query changes for responsive design.

Parameters

query
string
required
CSS media query string (e.g., ‘(min-width: 768px)‘)

Return Value

matches
boolean
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>
  );
}

Build docs developers (and LLMs) love