Reputation: 75
I have an array of 1000 min to 5000 max points to draw on my react-leaflet map. So my render function in the map component looks similar to:
renderMarkers = () => {
return markers.map(
(marker) => {
return <Marker key={`${marker.id}`} position={[marker.lt, marker.lg]} ></Marker>
}
)
}
render() {
<Map>
{this.renderMarkers()}
</Map>
}
My problem is that it takes normally 1 sec to 3 secs to render the html on the map and the user experience is horrible, since the window blocks a bit now and then when the map moves.
Is there anyway to divide all markers rendering in sections or let the window load that javascript async or show a loading icon while the map function runs?
Even if there is a better approach that the one that I am doing, would be great to know.
Thanks in advance
EDIT: does not have to do anything with clustering since it is already clustering the markers, has to do with showing somehow to the user that the javascript is running so he needs to wait, or render async so the map flows.
Upvotes: 3
Views: 4230
Reputation: 19069
Ah, the mistake of assuming that the reactive paradigm is better but forgetting that your function calls happen on every render()
call.
As a rule of thumb, if the same operation returns the same value every time, and your code is running that operation a lot of times, then you should cache the result (or at the very least consider caching the result).
That is pretty much universal, but applies specifically to your case: your code is recalculating an array of Marker
components (which becomes an expensive operation) on every render()
call, instead of when the marker data changes. So cache its results, with something like:
class Foo extends React.Component {
getDerivedStateFromProps(nextProps, prevState) {
if ( /* marker data has changed or */ !this._markerComponents) {
this._markerComponents = markers.map( (marker, key) =>
( <Marker key={`marker-${key}`} position={[marker.lt, marker.lg]} ></Marker> )
);
}
}
render() {
return ( <Map>{this._markerComponents}</Map> );
}
}
Upvotes: 3