Using React or Redux state in a ProseMirror Plugin

Suppose you have a ProseMirror text editor inside a React UI. Now you are writing a ProseMirror plugin, but you need access to some state from outside of ProseMirror, like from React or Redux. How do you have access to the latest values of that state without killing performance? It turns out you can pass data to your plugin from the React side of your code via a transaction with a specific metadata key set.

In the example below, I needed to calculate a set of decorations based on state from ProseMirror as well as state from Redux. This meant I needed the decorations to update when either the ProseMirror state changed, or the Redux state changed.

To pass in the updated Redux state, I dispatch a transaction with the updated state, which my plugin listens for. In this example I am using a React hook.

In the plugin, when there is a new transaction, we have to check whether the transaction is because the ProseMirror state was updated, or because the Redux state was updated. If the React state was updated, we save it in our plugin state and create the updated decorations. If the ProseMirror state was updated we can just create the new decorations because we always have access to the current ProseMirror state.

--

--

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