Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

164
Views
React how to not reinitalize mapbox gl js on page change

I am trying to keep the state of the map, to not rerender/initialize the map every time user returns to the map page.

I tried with context where i skip map initialization when map object is not empty, but then im getting blank map.

useEffect(() => {

const initializeMap = () => {
  const map = new mapboxgl.Map({
    container: mapContainerRef.current,
    style: "",
    center: [lng, lat],
    pitch: 59.49999999999986, // pitch in degrees
    bearing: -136.86837902659892, // bearing in degrees
    zoom: zoom,
  });


  map.on("load", () => {
    setMap(map);

    map.resize();
  });

  console.log("init");
};

if (!map) initializeMap(); }, [map]);

Is this possible? Help much appreciated

EDIT:

Found someone asking the same question: https://github.com/mapbox/mapbox-gl-js/issues/8687

Im still having trouble with the container ref, if anyone know how i can update container with preivious map container that would be helpful. I can get previous container by calling map.getContainer() just have no idea how to set it.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

replacing previous div with context map solves this for me:

map ? document.getElementById("map").replaceWith(map.getContainer()) : "";

// in return 

 <div id={"map-container"}>
        <div
          id={"map"}
          className="map-container"
          ref={(el) => (mapContainerRef.current = el)}
        />

Now the map does not reload when navigating between pages

Context implementation example from someone else: https://codesandbox.io/s/mapbox-react-popups-fd4d4?file=/src/components/Map.js

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!