Use React Context to Display Notifications

Share this video with your friends

Send Tweet

A common kind of “global” data is a toast or popup notification that appears in the corner of the app when some event happens. Allowing a deeply-nested component to surface a notification using props can be painful, but Context makes it much easier. In this lesson we’ll see how to dispatch a notification from a deeply-nested component and display it at the root level.

Dave Ceddia
Dave Ceddia(instructor)
~ 6 years ago

FYI: The 'before' code for this lesson is here if you need it.

Enoh Barbu
Enoh Barbu
~ 6 years ago
<NotificationProvider> <UserProvider> <EmailProvider> <Root /> </EmailProvider> </UserProvider> </NotificationProvider>

how ugly this is? very ugly, everything it's a provider?!?! just DON'T! don't use context anymore

Enoh Barbu
Enoh Barbu
~ 6 years ago
<NotificationProvider> <UserProvider> <EmailProvider> <Root /> </EmailProvider> </UserProvider> </NotificationProvider>
Dave Ceddia
Dave Ceddia(instructor)
~ 6 years ago

That’s just how I chose to organize the code here, to show how it could be split up. Feel free to combine them though!

You could merge the providers together into one Global provider (e.g. one provider holding state for emails, notifications, and user), or alternatively create a “wrapper” Provider which wraps its props.children with all 3 other providers.

Enoh Barbu
Enoh Barbu
~ 6 years ago

that sounds better, I haven't experienced yet this, but an example would help others too, I guess

Leox Fernandez
Leox Fernandez
~ 5 years ago

componentWillUnmount is not working on NotificationProvider class. Notifications still shows on logout.

Xavier Brinon
Xavier Brinon
~ 5 years ago

I'm really enjoying this course so far, thanks Dave!

Eric Laursen
Eric Laursen
~ 5 years ago

Hello there, Thanks for the great content, I learned a bunch! Here, maybe like Leox noted above, the notifications popup on the login page, which seems sort of out-of-place. Is this an out-of-scope issue for this video series, to make the notifications show-up only on the email-list page?

Thanks again