- 🚀 Global Access - Show alerts from anywhere in your app
- 📱 React Native Optimized - Built specifically for React Native
- 🎯 Priority System - HIGH alerts wait their turn (first in, first out); LOW alerts are best-effort
- 🎨 Fully Customizable - Custom styling and alert components
- ⚡ TypeScript Support - Full type safety out of the box
- 🔄 Smart Queue Management - Intelligent alert queuing with priority handling
- 🪝 React Hooks - Modern React patterns with useGlobalAlert hook
- 🎭 Multiple Alert Types - Error, Warning, Success, Info, Notice, Question, Loading, and Tips
- ⚙️ Flexible Configuration - Optional priority enforcement and backdrop dismiss
- 📚 Multiple Alerts - Show multiple alerts in sequence with
showMultiple - 🎨 Button Customization - Rich button styling and behavior options
- ⏱️ Auto Dismiss & Countdown - Close alerts automatically with
dismissIn, show the remaining seconds withuseAlertCountdown, extend or cancel the timer withupdate - 🔁 Live Updates - Change the alert that is on screen with
update(great for progress/loading) - 🧘 Render Friendly - Showing or hiding an alert only re-renders your modal, never your app tree
- React 18 or newer (React Native 0.69+)
npm install @hexhad/react-native-global-modalor
yarn add @hexhad/react-native-global-modalWrap your app with GlobalAlertProvider and provide your custom alert modal component:
import React from 'react';
import { GlobalAlertProvider, GlobalAlert } from '@hexhad/react-native-global-modal';
import CustomAlertModal from './components/CustomAlertModal';
export default function App() {
return (
<GlobalAlertProvider
AlertModal={CustomAlertModal}
ignorePriority={false} // Optional: set to true to always show latest alert
>
{/* Your app content */}
</GlobalAlertProvider>
);
}import React from 'react';
import { Modal, View, Text, TouchableOpacity, StyleSheet } from 'react-native';
import type { AlertModalProps } from '@hexhad/react-native-global-modal';
const CustomAlertModal: React.FC<AlertModalProps> = ({ visible, data, onClose }) => {
if (!data) return null;
return (
<Modal
visible={visible}
transparent
animationType="fade"
onRequestClose={data.backdropDismiss ? onClose : undefined}
>
<TouchableOpacity
style={styles.overlay}
activeOpacity={1}
onPress={data.backdropDismiss ? onClose : undefined}
>
<TouchableOpacity style={styles.container} activeOpacity={1}>
{data.title && <Text style={styles.title}>{data.title}</Text>}
{data.message && <Text style={styles.message}>{data.message}</Text>}
<View style={styles.buttonContainer}>
{data.buttons?.map((button, index) => (
<TouchableOpacity
key={index}
style={[styles.button, button.style, { backgroundColor: getButtonColor(button.variant) }]}
onPress={() => {
button.onPress?.();
if (button.closeOnPress !== false) {
onClose?.();
}
}}
>
<Text style={[styles.buttonText, button.textStyle]}>{button.title}</Text>
</TouchableOpacity>
))}
</View>
</TouchableOpacity>
</TouchableOpacity>
</Modal>
);
};
const getButtonColor = (variant?: string) => {
switch (variant) {
case 'ERROR': return '#FF6B6B';
case 'SUCCESS': return '#51CF66';
case 'WARNING': return '#FFD93D';
default: return '#339AF0';
}
};
const styles = StyleSheet.create({
overlay: {
flex: 1,
backgroundColor: 'rgba(0, 0, 0, 0.5)',
justifyContent: 'center',
alignItems: 'center',
},
container: {
backgroundColor: 'white',
borderRadius: 12,
padding: 20,
margin: 20,
minWidth: 280,
},
title: {
fontSize: 18,
fontWeight: 'bold',
marginBottom: 10,
textAlign: 'center',
},
message: {
fontSize: 16,
marginBottom: 20,
textAlign: 'center',
color: '#666',
},
buttonContainer: {
flexDirection: 'row',
justifyContent: 'space-around',
},
button: {
paddingHorizontal: 20,
paddingVertical: 10,
borderRadius: 6,
minWidth: 80,
},
buttonText: {
color: 'white',
fontWeight: 'bold',
textAlign: 'center',
},
});
export default CustomAlertModal;import { GlobalAlert } from '@hexhad/react-native-global-modal';
// Simple alert
GlobalAlert.show({
title: 'Success!',
message: 'Your action was completed successfully.',
type: GlobalAlert.TYPE.SUCCESS,
buttons: [
{
title: 'OK',
onPress: () => console.log('OK pressed'),
closeOnPress: true, // Default behavior
},
],
});
// High priority alert (replaces a LOW alert, waits behind other HIGH alerts)
GlobalAlert.show({
title: 'Critical Error',
message: 'Something went wrong!',
priority: GlobalAlert.PRIORITY.HIGH, // High priority
type: GlobalAlert.TYPE.ERROR,
buttons: [
{
title: 'Retry',
onPress: () => {
// Handle retry logic
console.log('Retrying...');
},
},
{
title: 'Cancel',
variant: 'ERROR',
onPress: () => console.log('Cancelled'),
},
],
});
// Alert with backdrop dismiss
GlobalAlert.show({
title: 'Info',
message: 'Tap outside to dismiss',
backdropDismiss: true,
buttons: [
{
title: 'Got it',
closeOnPress: true,
},
],
});
// Show multiple alerts in sequence
GlobalAlert.showMultiple([
{
title: 'First Alert',
message: 'This will show first',
type: GlobalAlert.TYPE.INFO,
buttons: [{ title: 'Next' }],
},
{
title: 'Second Alert',
message: 'This will show after the first is closed',
type: GlobalAlert.TYPE.SUCCESS,
buttons: [{ title: 'Done' }],
}
]);
// Auto dismiss after 2 seconds
GlobalAlert.show({
type: GlobalAlert.TYPE.SUCCESS,
message: 'Saved!',
dismissIn: 2000,
});
// Update the alert that is currently on screen
GlobalAlert.show({ type: GlobalAlert.TYPE.LOADING, message: 'Uploading… 0%' });
GlobalAlert.update({ message: 'Uploading… 50%' });
// Inspect the current state
GlobalAlert.isVisible(); // boolean
GlobalAlert.getCurrent(); // AlertData | null
// Hide current alert
GlobalAlert.hide();
// Clear all alerts (including queue)
GlobalAlert.clearAll();import React from 'react';
import { View, Button } from 'react-native';
import { useGlobalAlert } from '@hexhad/react-native-global-modal';
const MyComponent: React.FC = () => {
const alert = useGlobalAlert();
const showConfirmation = () => {
alert.show({
title: 'Confirm Action',
message: 'Are you sure you want to proceed?',
type: alert.TYPE.QUESTION,
priority: alert.PRIORITY.HIGH, // Ensure this shows immediately
buttons: [
{
title: 'Cancel',
onPress: () => console.log('Cancelled'),
closeOnPress: true,
},
{
title: 'Confirm',
variant: 'SUCCESS',
onPress: () => {
console.log('Confirmed!');
// Handle confirmation logic
},
closeOnPress: true,
},
],
});
};
return (
<View>
<Button title="Show Confirmation" onPress={showConfirmation} />
</View>
);
};Main provider component that manages the global alert system.
| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
AlertModal |
React.ComponentType<AlertModalProps> |
✅ | - | Your custom alert modal component |
children |
React.ReactNode |
❌ | - | Your app content |
types |
Record<string, string> |
❌ | {} |
Custom alert types (merged with defaults) |
globalAlert |
GlobalAlertInstance |
❌ | - | Custom global alert instance |
ignorePriority |
boolean |
❌ | false |
If true, always show the latest alert immediately |
Configuration object for alert content and behavior.
type AlertData = {
type?: string; // Alert type (ERROR, SUCCESS, etc.)
variant?: string; // Visual variant for buttons/styling
title?: string; // Alert title
message?: string; // Alert message
priority?: number; // Priority: 0 (LOW) or 1 (HIGH)
backdropDismiss?: boolean; // Allow dismissing by tapping backdrop
buttons?: AlertButton[]; // Array of action buttons
onClose?: () => void; // Callback when alert closes
dismissIn?: number; // Auto-close after this many milliseconds
[key: string]: any; // Additional custom properties
};Configuration for alert buttons.
type AlertButton = {
title?: string; // Button text
variant?: string; // Visual variant for styling
onPress?: () => void; // Button press handler
closeOnPress?: boolean; // Whether to close alert on press (default: true)
style?: any; // Custom button styles
textStyle?: any; // Custom button text styles
};Props passed to your custom modal component.
type AlertModalProps = {
visible: boolean; // Whether modal should be visible
data: AlertData | null; // Alert configuration data
onClose?: () => void; // Function to close the alert
expiresAt?: number | null; // Epoch ms when the alert auto-closes (dismissIn), else null
};Render a live countdown inside your modal without any timers of your own:
import { useAlertCountdown } from '@hexhad/react-native-global-modal';
const CustomAlertModal = ({ visible, data, onClose, expiresAt }: AlertModalProps) => {
const seconds = useAlertCountdown(expiresAt); // 0 when there is no deadline
// ...
<Text>{seconds > 0 ? `Close (${seconds})` : 'Close'}</Text>
};useAlertCountdown(expiresAt, intervalMs = 1000) returns the whole seconds left, re-rendering only the component that calls it, once per interval, and only while a deadline exists.
GlobalAlert.show({
title: 'Session expiring',
message: 'You will be logged out when the countdown ends.',
priority: GlobalAlert.PRIORITY.HIGH,
dismissIn: 10000,
onClose: logout,
buttons: [
{
title: 'Stay signed in',
closeOnPress: false,
onPress: () => GlobalAlert.update({ dismissIn: 10000 }), // restart the countdown
},
{ title: 'Log out' }, // closes → onClose runs
],
});GlobalAlert.TYPE: Predefined alert typesERROR,WARNING,SUCCESS,INFO,NOTICE,QUESTION,LOADING,TIP
GlobalAlert.PRIORITY: Priority levelsLOW: 0(Low priority - default)HIGH: 1(High priority)
GlobalAlert.show(options: AlertData): Show an alertGlobalAlert.showMultiple(options: AlertData[]): Show multiple alerts in sequenceGlobalAlert.hide(): Hide the current alertGlobalAlert.clearAll(): Hide current alert and clear the queueGlobalAlert.update(options: Partial<AlertData>): Merge new values into the alert currently on screen. PassdismissInto restart the auto-close timer (0cancels it); omit it to leave the timer untouched.GlobalAlert.isVisible(): Whether an alert is currently shownGlobalAlert.getCurrent(): The alert currently shown, ornull
React hook that provides access to the alert system within components.
const alert = useGlobalAlert();
// Returns: { show, showMultiple, hide, clearAll, update, isVisible, getCurrent, TYPE, PRIORITY }Note: The hook will throw an error if used outside of GlobalAlertProvider.
Only one alert is on screen at a time. What happens to a new alert depends on its priority and on what is currently showing.
- High Priority (
PRIORITY.HIGH = 1): Never lost. Shows immediately if nothing important is on screen, otherwise waits in line and is shown in arrival order (first in, first out). - Low Priority (
PRIORITY.LOW = 0): Default. Best effort - shown only when nothing else is on screen or waiting, and silently dropped or replaced otherwise. Use it for toasts and status messages that are fine to miss.
| Currently showing | New alert | Result |
|---|---|---|
| nothing | LOW or HIGH | Shows immediately |
| HIGH | HIGH | Waits; shown after the current one (and any already waiting) closes |
| LOW | HIGH | HIGH shows immediately; the LOW alert is discarded (its onClose is not called) |
| HIGH (or HIGH alerts waiting) | LOW | Dropped |
| LOW | LOW | The new one replaces it |
So show(HIGH 1), show(LOW 1), show(HIGH 2), show(LOW 2) in quick succession shows
HIGH 1, then HIGH 2 once it is closed; both LOW alerts are dropped.
Every alert waits its turn in a single first-in, first-out queue. Nothing is dropped or replaced.
- The next alert is shown 50ms after the previous one closes, so the modal can unmount cleanly
showMultiple([a, b, c])showsaunder the rules above and queuesbandcbehind it, in order, regardless of their priorityonCloseruns at most once per alert, after it has been hidden, so it can safely show another alert- Calling the
onCloseof an alert that is no longer on screen does nothing hide()closes the current alert and continues with the queue;clearAll()also empties it
const upload = async (file: File) => {
GlobalAlert.show({
type: GlobalAlert.TYPE.LOADING,
message: 'Uploading… 0%',
progress: 0, // custom property, read by your modal
priority: GlobalAlert.PRIORITY.HIGH,
// No buttons = user must wait for programmatic dismissal
});
await uploadFile(file, (percent) => {
// Only the modal re-renders; the timer and queue are untouched
GlobalAlert.update({ message: `Uploading… ${percent}%`, progress: percent });
});
// The loading alert is HIGH priority: hide it before showing the LOW
// result, otherwise the result is dropped while the HIGH alert is up.
GlobalAlert.hide();
GlobalAlert.show({
type: GlobalAlert.TYPE.SUCCESS,
title: 'Complete!',
message: 'Upload finished successfully.',
dismissIn: 2000,
});
};Your alert modal can access any custom properties you pass:
GlobalAlert.show({
title: 'Custom Alert',
message: 'This alert has custom properties',
customIcon: 'star', // Custom property
backgroundColor: '#f0f0f0', // Custom property
animationType: 'bounce', // Custom property
buttons: [
{
title: 'Styled Button',
style: {
backgroundColor: '#FF6B6B',
borderRadius: 20,
paddingHorizontal: 30,
},
textStyle: {
color: 'white',
fontWeight: 'bold',
fontSize: 16,
},
onPress: () => console.log('Custom button pressed'),
},
],
});const handleApiError = (error: Error, retryFn: () => void) => {
GlobalAlert.show({
title: 'Request Failed',
message: error.message || 'An unexpected error occurred.',
type: GlobalAlert.TYPE.ERROR,
priority: GlobalAlert.PRIORITY.HIGH, // Ensure it shows immediately
buttons: [
{
title: 'Retry',
variant: 'SUCCESS',
onPress: () => {
console.log('Retrying...');
retryFn();
},
},
{
title: 'Cancel',
variant: 'ERROR',
onPress: () => console.log('Operation cancelled'),
},
],
onClose: () => {
console.log('Error alert closed');
},
});
};const showDeleteConfirmation = (itemName: string, onConfirm: () => void) => {
GlobalAlert.show({
title: 'Delete Item',
message: `Are you sure you want to delete "${itemName}"? This action cannot be undone.`,
type: GlobalAlert.TYPE.QUESTION,
priority: GlobalAlert.PRIORITY.HIGH,
buttons: [
{
title: 'Cancel',
style: { backgroundColor: '#gray' },
onPress: () => console.log('Delete cancelled'),
},
{
title: 'Delete',
variant: 'ERROR',
onPress: () => {
console.log(`Deleting ${itemName}`);
onConfirm();
},
},
],
});
};const showMultipleAlertsDemo = () => {
GlobalAlert.showMultiple([
{
title: 'Welcome!',
message: 'Thank you for using our app',
type: GlobalAlert.TYPE.SUCCESS,
buttons: [{ title: 'Next' }],
},
{
title: 'New Features',
message: 'Check out what\'s new in this version',
type: GlobalAlert.TYPE.INFO,
buttons: [{ title: 'Continue' }],
},
{
title: 'Quick Tip',
message: 'You can customize alerts with your own styling',
type: GlobalAlert.TYPE.TIP,
buttons: [{ title: 'Got it!' }],
},
]);
};const showQueueDemo = () => {
// Low priority alert
GlobalAlert.show({
title: 'Low Priority 1',
message: 'This is a low priority alert',
priority: GlobalAlert.PRIORITY.LOW,
buttons: [{ title: 'OK' }],
});
// High priority alert (will interrupt)
setTimeout(() => {
GlobalAlert.show({
title: 'High Priority',
message: 'This high priority alert interrupts the low priority one',
priority: GlobalAlert.PRIORITY.HIGH,
buttons: [{ title: 'Got it' }],
});
}, 1000);
// Another high priority (will queue)
setTimeout(() => {
GlobalAlert.show({
title: 'Another High Priority',
message: 'This will be queued and shown after the first high priority alert',
priority: GlobalAlert.PRIORITY.HIGH,
buttons: [{ title: 'Understood' }],
});
}, 2000);
};// In your app setup
const customTypes = {
CUSTOM_SUCCESS: 'CUSTOM_SUCCESS',
MAINTENANCE: 'MAINTENANCE',
FEATURE_ANNOUNCEMENT: 'FEATURE_ANNOUNCEMENT',
};
<GlobalAlertProvider
AlertModal={CustomAlertModal}
types={customTypes}
>
{/* Your app */}
</GlobalAlertProvider>
// Usage
GlobalAlert.show({
type: 'CUSTOM_SUCCESS', // or GlobalAlert.TYPE.CUSTOM_SUCCESS
title: 'Feature Updated!',
message: 'Check out the new functionality.',
});import { createGlobalAlert } from '@hexhad/react-native-global-modal';
const customAlert = createGlobalAlert({
SPECIAL: 'SPECIAL',
NOTIFICATION: 'NOTIFICATION',
});
// Use the custom instance
customAlert.show({
type: customAlert.TYPE.SPECIAL,
title: 'Special Alert',
message: 'This uses a custom alert instance',
});class ErrorBoundary extends React.Component {
componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
GlobalAlert.show({
title: 'Application Error',
message: 'Something went wrong. The app will reload.',
type: GlobalAlert.TYPE.ERROR,
priority: GlobalAlert.PRIORITY.HIGH,
buttons: [
{
title: 'Reload App',
onPress: () => {
// Reload or restart logic
window.location.reload();
},
},
],
});
}
render() {
return this.props.children;
}
}The library is fully typed with comprehensive TypeScript definitions:
import type {
AlertData,
AlertButton,
AlertModalProps,
AlertModalRef,
GlobalAlertInstance,
GlobalAlertProviderProps,
Priority
} from '@hexhad/react-native-global-modal';
// Example: Typed custom alert function
const showTypedAlert = (config: AlertData): void => {
GlobalAlert.show({
...config,
priority: config.priority ?? GlobalAlert.PRIORITY.LOW, // Default to low priority
});
};- Use High Priority Sparingly - Reserve
PRIORITY.HIGHfor critical alerts that must interrupt the user - Provide Clear Actions - Always include actionable buttons unless the alert is purely informational
- Handle onClose Properly - Use
onClosecallback for cleanup when alerts are dismissed - Custom Properties - Leverage custom properties to pass additional data to your modal component
- Error Handling - Always handle button press errors gracefully
- Queue Management - Consider using
ignorePriority={true}for simpler queue behavior if priority handling isn't needed - Backdrop Dismiss - Use
backdropDismissfor non-critical alerts to improve UX - Multiple Alerts - Use
showMultiple()for onboarding flows or sequential information - Button Variants - Use consistent button variants across your app for better UX
-
"GlobalAlert.show called before GlobalAlertProvider mounted"
- Ensure
GlobalAlertProviderwraps your app at the root level - Don't call
GlobalAlert.show()during app initialization before the provider mounts
- Ensure
-
"useGlobalAlert must be used within a GlobalAlertProvider"
- The
useGlobalAlert()hook can only be used inside components wrapped byGlobalAlertProvider
- The
-
Alerts not showing
- Check that your
AlertModalcomponent properly handles thevisibleprop - Ensure your modal component renders when
datais not null
- Check that your
-
Queue not working as expected
- Review the priority system documentation
- Consider using
ignorePriority={true}for simpler behavior
-
Backdrop dismiss not working
- Ensure your modal handles
onRequestCloseand touch events on the backdrop - Check that
backdropDismissis set totruein your alert data
- Ensure your modal handles
Version 0.4 is a rewrite of the queue core. The public API is unchanged and purely additive,
but the internals moved out of React state into a small external store that only the modal
host subscribes to (useSyncExternalStore). Measured in Jest against 0.3.x with the same
harness:
| Metric | 0.3.x | 0.4 |
|---|---|---|
| Modal re-renders when the app tree re-renders 20x (navigation, theme, store updates) | 20 | 0 |
| Modal renders per show → auto-close cycle | 2 | 2 |
setTimeouts created per dismissIn alert |
2 (duplicate) | 1 |
Renders for 10 rapid show() calls in one tick |
1 | 1 |
What that means in practice:
- Your
AlertModalno longer re-renders with the rest of your app. Previously it re-rendered on every render of whatever wrapped the provider; now only when an alert actually changes. - No duplicate or leaked timers. One timer per timed alert; the 50ms "show next" timer is cancelled and collapsed instead of re-scheduled on every close.
- One code path for show/queue instead of three copies, covered by 24 unit tests.
Bugs fixed on the way (each had a failing test against 0.3.x):
useGlobalAlert()always threw — the provider never supplied the context.- The
typesandglobalAlertprovider props were ignored. onClosecould fire twice (e.g. a default OK button whoseonPressisonCloseand that also closes viacloseOnPress).- A stale
onClosefrom a replaced alert could close the newer alert. - Showing an alert from inside
onClosehid it immediately. showMultipleshowed only the last LOW alert instead of the whole sequence.- Alerts shown from a child's mount effect hit "provider not mounted".
- Toggling
ignorePrioritywiped the queue.
Trade-offs to be aware of:
- Requires React 18+ (React Native 0.69+) for
useSyncExternalStore. - The queue semantics changed on purpose — see the migration guide below.
Nothing is removed. Existing GlobalAlert.show / hide / clearAll / showMultiple calls,
GlobalAlertProvider props and AlertModal components keep compiling and running. Three
behaviours changed, and three new props/methods are worth adopting.
| Situation | 0.3.x | 0.4 |
|---|---|---|
| HIGH on screen, new HIGH arrives | New one shows immediately; old one re-queued | New one waits; shown after the current closes |
| Queue order | LIFO (most recent first) | FIFO (arrival order) |
| HIGH on screen (or waiting), new LOW arrives | LOW shows immediately; HIGH re-queued and reappears later | LOW is dropped |
| LOW on screen, new HIGH arrives | HIGH shows; LOW discarded | same |
| LOW on screen, new LOW arrives | newest replaces | same |
ignorePriority={true} |
newest always interrupts, LIFO | single FIFO queue, nothing dropped |
showMultiple([a, b, c]) |
effectively only c for LOW items |
a, then b, then c |
What to check in your app:
-
Anything the user must see or answer must be
PRIORITY.HIGH. A LOW alert fired while a HIGH one is up (an API error, say) is now dropped instead of jumping in front. -
Replacing a HIGH alert with another (loading → result) needs an explicit
hide()first, because a new HIGH no longer interrupts:GlobalAlert.show({ type: 'LOADING', priority: GlobalAlert.PRIORITY.HIGH, message: 'Saving…' }); await save(); GlobalAlert.hide(); // ← new in 0.4 GlobalAlert.show({ type: 'SUCCESS', message: 'Saved', dismissIn: 2000 });
-
If you relied on a HIGH alert coming back after a LOW toast closed, that no longer happens (the toast is dropped instead). Make the toast HIGH if it must show afterwards.
-
If you depended on
showMultipleshowing only the last item, pass just that item.
Modal code that worked around double onClose calls (guards, closed flags) can be
removed. onClose is now safe to call from a button's onPress and again via
closeOnPress; the second call is a no-op.
Bump React if you are below 18. There is no other install step.
expiresAtprop on your modal +useAlertCountdown(expiresAt)for "Close (5)" buttons.GlobalAlert.update(partial)to change the alert on screen (progress, messages) without re-showing it; passdismissInto restart the auto-close timer.GlobalAlert.isVisible()/getCurrent()for async code that needs to know whether an alert is up.useGlobalAlert()now works, and itsTYPEincludes the provider's customtypes.
See the contributing guide to learn how to contribute to the repository and the development workflow.
MIT
Made with ❤️ for the React Native community