React native map markers flicker on state update

4.8k views Asked by At

We've multiple coordinates that we need to display on the map using markers. The marker clicked by the user has to be marked as active and have some operations performed for some other functionality.

When I update the state in onPress method of the marker all the markers flickers, probably due to re-rendering. I've added the unique key as well but it doesn't seem to work.

I've an array named markers which is used to render the markers on the map.

return markers.map(marker => (
      <Marker
        tracksViewChanges={false}
        tracksInfoWindowChanges={false}
        animationEnabled={false}
        identifier={marker.id}
        key={marker.id}
        coordinate={{
          latitude: marker.location.latitude,
          longitude: marker.location.longitude,
        }}
        onPress={() => {
          setActiveMarker(marker.id);  // State update using hook
        }}>
        //Rendering the custom marker image here
        {if(activeMarker === marker.id)
        (<Icon
          width={22}
          height={32}
          source={require('../../assets/images/marker.png')})
        else
         (<Icon
          width={22}
          height={32}
          source={require('../../assets/images/activeMarker.png')})
         }
        />
      </Marker>
));

The react-native-map version: 0.27.1

2

There are 2 answers

3
kkk On

You can use React.memo to avoid expensive rendering.

https://reactjs.org/docs/react-api.html#reactmemo

const Markers = React.memo(({markers}) => {
  return markers.map( ... );
})
0
Nino Bouchedid On

For anyone seeing their markers flicker upon selection (if you change its style when selecting it), make sure you don't have two markers overlapped at the same exact position. I had this weird flickering issue and spent an hour trying to figure out what was going on, turns out I duplicated my dummy data and had two markers overlapped in every position