A Convenient Way to Display Messages in React Apps

Noraiz Sardar
Red Buffer
Published in
3 min readMar 16, 2023

I work in React often to build the front-end of my applications which means I have a choice of choosing from hundreds of UI libraries. One of our current projects is based around insurance and litigation technology. The application was fairly complex hence it had complicated user flows and a lot of reusable components. So after some due diligence and careful requirement analysis, we decided to use Material UI (MUI) to build the front-end of our application.

Coming from Ant Design system to MUI, at first it feels like a lot of scratch code needs to be written to achieve a simple task e.g., forms - with no out-of-the-box component to work with forms. An interesting habit I developed with Ant was using an imperative style of writing simple logic like using useMessage, useNotification hooks to show messages and notifications. But MUI does not provide any out-of-the-box solution. After a bit of googling, I came across a library notistack that lets us achieve this style. But bundlephobia is a thing! And I want to reduce my module’s footprint as well. With that in mind, I decided to make a bare-bone imperative API to achieve this task.

I created a simple component called AppContext, which resides in the src directory.

This will show the snackbar component whichever component calls the useMessage hook. Check the code below for useMessage hook.

Code for useMessage hook
src/custom/hooks/use-message.tsx

This is a vanilla version of the useMessage hook. You can customise it as much as you want with passing parameters, that extend SnackbarProps. Now you can call this hook anywhere in your component like this:

using useMessage hook
src/page/use-invitation-form.tsx

You must have noticed that we are using Redux store to manage our snackbar display logic, now let’s look at how we have configured it with Redux.

redux configuration in AppContextSlice
src/store/app-context-slice.tsx

Finally, we have added AppContext component in our root component like this:

src/index.tsx

This is a simple and intuitive way to create an imperative style API using React hooks to display messages. An interesting fact about the AppContext component, you can use the provider pattern in React and wrap the app component inside AppContext. I didn’t do it to avoid confusion, since Context API also wraps the app component and we are using Redux. You can also add hooks to manage open dialog boxes, handle async logics inside AppContext and keep the individual components clean and it will ensure the reusability as well.

Noraiz is a software engineer at Red Buffer.

--

--

Noraiz Sardar
Red Buffer

I am a software engineer working primarily with web technologies. I have interest in software design and architecture.