1

In my React Native app, I fetch the markers that should be shown based on region. So when the region changes, a new fetch is called and all the markers are redrawn. In order to optimize the performance, I'd like to draw only the new fetched markers that weren't in the previous focused region, and delete the ones that are not visible anymore, keeping the ones that didn't change. How can I achieve this?

This is my relevant code:

import {View} from "react-native";
import {Marker} from "react-native-maps";
import MapView from "react-native-map-clustering";
import * as React from "react";
import {useState} from "react";

export default function MapScreen({navigation, route}) {

    const [placePins, setPlacePins] = useState([]);

    async function loadNewPlaces(region) {
        await fetch(...)
            .then(res => res.json())
            .then(data => {
                setPlacePins(data);
            })
            .catch(console.error)
        }
    };

    const mapPlaceMarkers = () => {
        return placePins.map((marker) => <Marker
            key={marker.id}
            coordinate={marker.coordinates}
            title={marker.name}
            onCalloutPress={() => {getPlace(marker.id + '-' + marker.repository)}}
        >
            {getPlaceMarkerPicture(marker)}

        </Marker>);
    };

    async function getPlace(place) {
        /* ... */
    }

    const getPlaceMarkerPicture = (marker) => {
        /* ... */
    };

    return (
        <View>            
            <MapView
                onRegionChangeComplete={(region) => loadNewPlaces(region)}>
                {mapPlaceMarkers()}
            </MapView>
        </View>
    );
}
cottontail
  • 10,268
  • 18
  • 50
  • 51
dondopong
  • 11
  • 2

0 Answers0