maxnamd
maxnamd

Reputation: 1

How to stop the Map flicker when state change?

I have a collection of locations, and whenever I update the index to navigate through them, my map flickers or re-renders. How can I prevent this flickering or unnecessary rendering?

const [currentIndexTS, setCurrentIndexTS] = useState(-1);
  const [isPlaying, setIsPlaying] = useState(false);
  const [playerSpeed, setPlayerSpeed] = useState(10);

  useEffect(() => {
    let timerId;

    if (isPlaying) {
      timerId = setInterval(() => {
        if (currentIndexTS < locationData.length - 1) {
          setCurrentIndexTS((prevIndex) => prevIndex + 1);
        } else {
          setIsPlaying(false);
        }
      }, playerSpeed);
    }

    return () => clearInterval(timerId);
  }, [currentIndexTS, isPlaying, locationData, playerSpeed]);

  const togglePlay = () => {
    setIsPlaying((prevState) => !prevState);
  };

  const resetMarkers = () => {
    setIsPlaying(false);
    setCurrentIndexTS(-1);
  };

  const markers = useMemo(
    () =>
      locationData.map((location, index) => (
        <React.Fragment key={`route-${index}`}>
          <Marker
            key={`marker-${index}`}
            position={{ lat: location.latitude, lng: location.longitude }}
            title={'Destination marker'}
            options={{
              visible: currentIndexTS >= index,
            }}
          />
        </React.Fragment>
      )),
    [locationData, currentIndexTS],
  );

return (
    <LoadScript googleMapsApiKey="APIKEY">
      <GoogleMap
        mapContainerClassName="mapContainer"
        mapContainerStyle={containerStyle}
        center={center}
        zoom={10}
        options={mapOptions}
      >
        {markers}
      </GoogleMap>
    </LoadScript>
  );

Already tried useRef and useCallback and memoized the markers but still every time the index changes and the map will flicker.

Upvotes: 0

Views: 68

Answers (0)

Related Questions