In this article I want to tell you how we can add to an application made with React a warning system like the one that Gmail implements to notify the different actions we do on emails:
For this we will use the React API Context and hooks, which will allow us to implement this feature in very few steps and in a simple way.
I think it is a very interesting exercise to practice with these two React features, so I hope you find it interesting. At the end of the article you can find a link to the project’s CodeSandbox in case you want to see what I tell you in this article in more detail.
Let’s go there!
Creating the ToastContext
The first thing we will do is create our
ToastContext inside the
Let’s see its content first and then we will explain the most relevant parts:
- In line 8 we will use the hook
useStateto store the active toasts in our application.
- Line 10 is where the magic happens (🧙♂️) thanks to the hook
useEffect. Every time the value of the variable toasts is modified by means of the
setToastsfunction of the hook
useState, this effect will be executed, which will set a counter (
setTimeout) so that after 3 seconds it removes the first toast from the list.
- In line 20 we define the
addToastfunction that will be the value that we will store later in the context (line 28). This function is memorized by means of the hook
useCallbackso that we do not recreate it every time the context changes and thus optimize the times that the components included in the context are “rendered”.
- Finally in line 28 we return the
childrenproperty wrapped by the
ToastContext.Providerto which we will add the block in charge of showing the active toasts.