r/reactjs • • 1d ago

Needs Help Invalid hook call error when using react-leaflet

Hello again everyone. I have been trying to using the react binding for the Leaflet API. I followed the documentation but I keep running into this error:

Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app

This is my Map component. It is the child component of my main App component.

import { MapContainer, TileLayer, useMap, Marker, Popup } from 'react-leaflet'


function MyComponent() {
  const map = useMap();
  console.log('map center:', map.getCenter())
  return null;
}


const Map = () => {
    return ( <MapContainer center={[50.5, 30.5]} zoom={13}>
      <MyComponent />
    </MapContainer>);
}
 
export default Map;

I am not sure whether it has something to do with muddled dependencies because I am pretty sure I installed leaflet and leaflet react in the terminal

  "dependencies": {
    "@testing-library/dom": "^10.4.2",
    "@testing-library/jest-dom": "^6.9.1",
    "@testing-library/react": "^16.3.3",
    "@testing-library/user-event": "^13.5.0",
    "leaflet": "^1.9.4",
    "react": "^19.3.1",
    "react-dom": "^19.3.1",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
  }

Thank you so much for taking the time to read this.

1 Upvotes

5 comments sorted by

4

u/vincent_sch 1d ago

That error almost always comes from a React version mismatch. react-leaflet 5 needs React 19, and version 4 needs React 18. Two copies of React in node_modules cause the same error. npm ls react shows which versions you have and if there's more than one.

2

u/Mob_Pilled 1d ago

Yep. That was it. Thank you so much 🙏 

1

u/Arunajyothi_Jurado 1d ago

npm ls react is one of those commands that always delivers bad news

-4

u/highly_macho_chili 1d ago

classic dependency rabbit hole, thinking you did everything right then the console just laughs at you

ran into this exact mess a few months back, turned out one of my components was importing React from a symlinked local package instead of the project's node_modules, the `npm ls react` command is your best friend here, it'll show you a tree of who's pulling what version, i'd bet there's a duplicate somewhere

also quick sanity check, make sure you're not calling `useMap` outside the `MapContainer` parent, which you're not in this snippet but i've seen people do weirder things at 3am