React-leaflet: how to update marker positions?

I can’t understand how to update my markers correctly using react-leaflet. Using this example:

import React from 'react';
import { render } from 'react-dom';
import { connect } from 'react-redux';
import { Map, Marker, TileLayer } from 'react-leaflet';

const map = props => (
  <Map center={[51.505, -0.09]} zoom={13}>
    <TileLayer
      url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
      attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
    />
    {props.markers.map(m => (
      <Marker position={m.position} />
    ))}
  </Map>
);

const mapStateToProps = state => ({
  markers: state.markers // array of objects with positions. this can change
});

render(connect(mapStateToProps)(map), document.getElementById('map-container'));

This works, but I don’t know if it’s the correct way of doing it. Because in that case when the markers update their position (or there are more markers), Leaflet will remove the markers and put new ones, instead of updating the position of the original markers.

So my question is that. Am I doing it right or this is not the most performant way?

Thanks!

Answer

Am I doing it right?

Yes, you are. You are supposed to use it this way.

this is not the most performant way

You are right there as well. This is not the most performant way. It is because once the props change, it will force a re-render of the react component. That will include the removal of the markers that were present and the addition of all the new markers. This is because React will have no idea on what is from the previous props and what are the new things.

You can fix that by using keys while mapping your data. Read more about it here

Another way would be to calculate your addedMarkers, removedMarkers and updatedMarkers separately and use them to re-render your view. That, however, can turn out to be a big hassle if there are a fairly lesser number of markers your app is going to use.