New Jan 5, 2025

How to properly handle snackbars in React when navigating between pages using notistack?

Libraries, Frameworks, etc. All from Newest questions tagged reactjs - Stack Overflow View How to properly handle snackbars in React when navigating between pages using notistack? on stackoverflow.com

I am working on a React project using the notistack library to display snackbars. I have a ProfilePage component where I show two snackbars based on specific data when the page is visited. However, I also want the snackbars to close automatically when the user navigates away from the page. If the user returns to the ProfilePage, the snackbars should reappear without issues.

Currently, the snackbars behave unexpectedly:

When I navigate away from the ProfilePage, the snackbars do close, but when I return to the ProfilePage, the snackbars reappear briefly and close immediately, which is not the desired behavior.

I suspect the issue lies in how notistack handles the snackbars when navigating between pages and how React mounts/unmounts components.

I’ve attempted several approaches, including:

  1. Using useEffect for opening and closing snackbars, with cleanup logic to close snackbars when the component unmounts.
  2. Using useRef to track whether the component has mounted to prevent snackbars from reopening unnecessarily.
  3. Ensuring that snackbars only open when certain conditions are met (e.g., checking data.count15Days or data.countExpired).

Here’s a simplified version of my code:

ProfilePage Component:

export default function ProfilePage() {
  const { user } = useUserStore();
  if (!user) return;

return ( <div> <ProfilePageStatistics /> </div> ); }

ProfilePageStatistics Component:

import { useEffect, useRef } from 'react';
import { useSnackbar } from 'notistack';

export default function ProfilePageStatistics() { const { data } = userGetStatistics(); // Fetching data const { enqueueSnackbar, closeSnackbar } = useSnackbar(); const isMounted = useRef(false);

const messages = { expiring: 'Less than 15 days remaining', expired: 'Expired', };

useEffect(() => { if (!isMounted.current) { isMounted.current = true; return; }

if (data?.count15Days) { enqueueSnackbar(messages['expiring'], { variant: 'certificateStatus', persist: true, }); }

return () => closeSnackbar(); }, [data?.count15Days]);

useEffect(() => { if (!isMounted.current) { isMounted.current = true; return; }

if (data?.countExpired) { enqueueSnackbar(messages['expired'], { variant: 'certificateStatus', persist: true, }); }

return () => closeSnackbar(); }, [data?.countExpired]);

return <div>Profile Statistics Content</div>; }

What I Want to Achieve

  1. Snackbars should open when the user visits the ProfilePage for the first time.
  2. Snackbars should close automatically when the user navigates to another page.
  3. If the user navigates back to the ProfilePage, snackbars should reopen and behave normally without closing immediately.
Scroll to top