What is a better way to initialise Mapbox map in ReactJS?

749 Views Asked by At

When creating a ReactJS map application based on Mapbox GL JS/MapLibre, I've met two different implementations for map initialisation:

1) hook-based (using useEffect)

import React, { useEffect, useRef, useState } from "react";
import "./App.css";
import mapboxgl from "mapbox-gl";
function App() {
  const [lng, setLng] = useState(5);
  const [lat, setLat] = useState(34);
  const [zoom, setZoom] = useState(2);
  const node = useRef(null);
  useEffect(() => {
    const map = new mapboxgl.Map({
      container: node.current,
      style: "mapbox://styles/mapbox/streets-v11",
      center: [lng, lat],
      zoom: zoom,
    });
  }, []);
  return (
    <div>
      <div ref={node} className="mapContainer" />
    </div>
  );
}
export default App;

2) return-embedded

import * as React from 'react';
import {render} from 'react-dom';
import Map, {Marker} from 'react-map-gl';

import 'mapbox-gl/dist/mapbox-gl.css';

const MAPBOX_TOKEN = ''; // Set your mapbox token here

function Root() {
  return (
    <Map
      initialViewState={{
        latitude: 37.8,
        longitude: -122.4,
        zoom: 14
      }}
      style={{width: 800, height: 600}}
      mapStyle="mapbox://styles/mapbox/streets-v9"
      mapboxAccessToken={MAPBOX_TOKEN}
    >
      <Marker longitude={-122.4} latitude={37.8} color="red" />
    </Map>
  );
}

render(<Root />, document.body.appendChild(document.createElement('div')));

Actually there is also a third one (via class-based component), but I believe it's kind of analogue to hook-based but using the class paradigm.

Are there any benefits/deficiences of using the 1st method over 2nd? What is the best practice?

0

There are 0 best solutions below