Search code examples
javascriptreactjsfrontendvite

STRUGGLING WITH NOTIFICATION COMPONENT


My English may be bad. I am working on a small personal project using vite. I have a notification component for showing notifications to the user. Currently I am calling the notification componentin every component where I have to give notifications like below.

  const [notification, setNotification] = useState(null);
return (
{notification && <Notification type={notification.type} message={notification.message} />}
  )

I know this not efficient as I am rendering the notification component, everytime I need in every component.

Is there any other approach to implement this so I don't need to render notification everytime I need. I am using zustand for state management. Is there any way we can use state management in a way that when I set a state of Notification store the component should be displayed or not.


Solution

  • Move your notification component to a parent component. This parent will be in charge of showing the notifications—think of it as the notification manager. Since you're using Zustand, you won't need to worry about prop drilling to pass data around. The parent component can update the Zustand store, and your notification component (wherever it's rendered) can listen for changes to that store.