Skip to main content
Context providers manage global state and functionality that needs to be accessible throughout the app.

ToastContext

Provides a global toast notification system for displaying temporary messages to users.

Setup

Wrap your app with the ToastProvider to enable toast notifications throughout your application:
import { ToastProvider } from '@/components/context/ToastContext';

export default function RootLayout() {
  return (
    <ToastProvider>
      {/* Your app content */}
    </ToastProvider>
  );
}

useToast Hook

The useToast hook provides access to the toast functionality.

Return Value

addToast
(message: string, type?: ToastType) => void
Function to display a toast notification.Parameters:
  • message (string, required): The text to display in the toast
  • type (ToastType, optional): The type of toast. Defaults to "info". Options:
    • "success" - Green background for success messages
    • "error" - Red background for error messages
    • "warning" - Yellow background for warning messages
    • "info" - Blue background for informational messages

TypeScript Interfaces

export type ToastType = "success" | "error" | "info" | "warning";

export interface Toast {
  id: string;
  message: string;
  type: ToastType;
}

interface ToastContextType {
  addToast: (message: string, type?: ToastType) => void;
}

Usage Examples

import { useToast } from '@/components/context/ToastContext';

function MyComponent() {
  const { addToast } = useToast();

  // Success toast
  const handleSuccess = () => {
    addToast('Operation completed successfully!', 'success');
  };

  // Error toast
  const handleError = () => {
    addToast('Something went wrong', 'error');
  };

  // Warning toast
  const handleWarning = () => {
    addToast('Please review your input', 'warning');
  };

  // Info toast (default)
  const handleInfo = () => {
    addToast('Here is some information');
    // or explicitly
    addToast('Here is some information', 'info');
  };

  return (
    <View>
      <Button title="Show Success" onPress={handleSuccess} />
      <Button title="Show Error" onPress={handleError} />
      <Button title="Show Warning" onPress={handleWarning} />
      <Button title="Show Info" onPress={handleInfo} />
    </View>
  );
}

Form Validation Example

import { useToast } from '@/components/context/ToastContext';

function LoginForm() {
  const { addToast } = useToast();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const handleSubmit = async () => {
    // Validation
    if (!email || !password) {
      addToast('Please fill in all fields', 'warning');
      return;
    }

    try {
      await login(email, password);
      addToast('Login successful!', 'success');
    } catch (error) {
      addToast('Invalid credentials', 'error');
    }
  };

  return (
    <View>
      <TextInput
        value={email}
        onChangeText={setEmail}
        placeholder="Email"
      />
      <TextInput
        value={password}
        onChangeText={setPassword}
        placeholder="Password"
        secureTextEntry
      />
      <Button title="Login" onPress={handleSubmit} />
    </View>
  );
}

API Request Example

import { useToast } from '@/components/context/ToastContext';

function DataManager() {
  const { addToast } = useToast();

  const saveData = async (data: any) => {
    try {
      const response = await fetch('/api/save', {
        method: 'POST',
        body: JSON.stringify(data),
      });

      if (response.ok) {
        addToast('Data saved successfully', 'success');
      } else {
        addToast('Failed to save data', 'error');
      }
    } catch (error) {
      addToast('Network error occurred', 'error');
    }
  };

  const deleteData = async (id: string) => {
    addToast('Are you sure?', 'warning');
    // Implement delete logic
  };

  return (
    <View>
      {/* Your component UI */}
    </View>
  );
}

Toast Behavior

  • Toasts appear at the top of the screen (60px from top)
  • Automatically dismiss after 3.5 seconds
  • Can be manually dismissed by tapping
  • Multiple toasts stack vertically
  • Smooth slide and fade animations
  • High z-index ensures visibility above other content

Error Handling

The useToast hook will throw an error if used outside of a ToastProvider:
if (!context) {
  throw new Error("useToast must be used inside ToastProvider");
}
Always ensure your component tree is wrapped with ToastProvider before using the useToast hook.

Build docs developers (and LLMs) love