How to use React’s new Context API to easily manage modals

How many times have you been frustrated with having to add another item in your React state along with 2 functions for opening and closing a modal ? Not to mention if you have multiple modals or you need to send them different params based on a user’s action.

From React 16.3 you can leverage the new Context API to solve this issue.

First let’s start with the stateful way of working with modals which you are probably familiar. Below there is an example on how you would implement that using react-modal.

Before getting our hands dirty and start implementing the new way of working with modals you should know how context works, the best place to learn this is from the docs.

We will start with creating a new Context with a default value which is an object.

  • component: the modal component that we want to render
  • props: the props that we want to set on the modal component
  • showModal: a function that will show the modal
  • hideModal: a function that will hide the modal

Next we will create a ModalProvider component that wraps the context provider because we need to have some state for showing and hiding the modal.

You might notice that we defined the the showModal and hideModal functions before the state, that’s because of how the class fields are evaluated.

For the consumer we just export the one from context.

Now that we have our modal provider and consumer we need a place in our app to display the modals, let’s call it ModalRoot.

In the ModalRoot we use the consumer to access the value in the context and see if there is any component that we need to render, along with props and the hide modal function.

Next we need to wrap our app with the ModalProvider in order to able to use the ModalConsumer.

Just one more thing left to do, actually using the ModalConsumer to display modals.

Below you can see you can see an example with working modals through context.

Hope you found this way of working with modals useful, just want to mention that at first this may seem a lot of work to just display a modal but you will truly start to see the benefits in working this way with modals when your app will start getting big and modal state will be all over the place.

I develop experiences on the mobile and web

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