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.