sp/src/hooks/useToast.js

36 lines
853 B
JavaScript

import { useState, useCallback } from 'react';
/**
* Custom hook for managing toast notifications
* @param {number} duration - Duration in ms to show the toast (default: 3000)
* @returns {Object} - Toast state and methods
*/
const useToast = (duration = 3000) => {
const [toast, setToast] = useState({
visible: false,
message: ''
});
// Show a toast notification
const showToast = useCallback((message) => {
setToast({ visible: true, message });
// Auto-hide the toast after the specified duration
setTimeout(() => {
setToast({ visible: false, message: '' });
}, duration);
}, [duration]);
// Hide the toast notification
const hideToast = useCallback(() => {
setToast({ visible: false, message: '' });
}, []);
return {
toast,
showToast,
hideToast
};
};
export default useToast;