Member-only story

React toast. An implementation with the Context API and hooks

How to add Gmail toasts to our React application using hooks and the Context API

--

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 contexts/ToastContext file.

Let’s see its content first and then we will explain the most relevant parts:

  • In line 8 we will use the hook useState to 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 setToasts function 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 addToast function that will be the value that we will store later in the context (line 28). This function is memorized by means of the hook useCallback so 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 children property wrapped by the ToastContext.Provider to which we will add the block in charge of showing the active toasts.

--

--

Gerardo Fernández
Gerardo Fernández

Written by Gerardo Fernández

Entre paseo y paseo con Simba desarrollo en Symfony y React

Responses (3)

Write a response