24
Managing mapbox-gl state in React app
In the course of my work at geoalert.io, I have repeatedly encountered the problem of managing the state of an application in
React
with a built-in mapbox-glI plan to cover the topic in a series of articles, including this one:
mapbox-gl
state in React
appmapbox-gl
in React
with Next.js
React
application with mapbox-gl
using XState
The last two articles mentioned correspond to the 2 main problems I encountered while using
mapbox-gl
in React
mapbox-gl
in React
- storing the built-in mapbox-gl
instance and making it accessible from other app componentsReact
app with mapbox-gl
- since mapbox-gl
has an internal state, you need to synchronize it with the state of the app itselfThere are several options for solving this problem, here are the most popular among them:
- Implementing as a
React Component
- Storing the map instance outside of
React
The most popular among them
- Steep learning curve, having sufficiently rich functionality, including for managing state, it is rather difficult to understand the library api
- Has almost 1MB bundle size, which is quite a lot
mapbox-gl
The main idea of this approach is to create a web map component, which must contain a
DOM
node for initializing the map, initialization logic, and it must also store an instance of the created mapContinuation and more detailed consideration of this issue, with various examples of implementation, wait in the next article
An example of such an implementation will also be considered in the next article
As a rule, tutorials on using
mapbox-gl
in React
end after the method of integrating the first into the second is described, articles about state management in such applications are rare, most articles on this topic are outdated at the momentThis article describes an example of state management with Redux using React class components
As mentioned above
mapbox-gl
has internal state for example properties such asUsually in the application interface, in addition to the map itself, there are elements whose display depends on the internal state of the map, for example, an element that displays the current coordinates and zoom, as in the above example

In addition to the state inside the map instance, the application can also have its own internal state, in our case, XState will be used for this
I'll cover this in more detail with an example of using
XState
in my next postUseful links:
24