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

Creating the ToastContext

The first thing we will do is create our ToastContext inside the contexts/ToastContext file.

  • 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.

Creating the hook useToastContext

Now that we have our context defined, we will create a custom hook that allows us to use it wherever we need it. Its code is very simple:

Adding toasts to the app

With all this beach bar set up, all you have to do is wrap the components you want with the ToastContextProvider component so that they can access the addToast function and thus add toasts when they need it.

  • useCallback to memorize the addAlert function.
  • useContext to access the ToastContext context from our components.
  • useState to store the toasts in our context.

Final thoughts

I wanted to share this mini project with you because I think it is very very interesting to review the 4 of the 5 React hooks while we implement very interesting functionality for our application through the React Context API.

Do you want to read more articles like this?

If you liked this article I encourage you to subscribe to the newsletter that I send every Sunday with similar publications to this and more recommended content: 👇👇👇

Entre paseo y paseo con Simba desarrollo en Symfony y React

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store