1

Is there a way to stop react re-rendering if only part of state changes?

The problem is that every time I hover on a marker a popup is opened or closed and it causes all the markers to re-render even though mystate is not changing only activePlace state is changing. console.log(myState); is running every time I hover in and out of the marker.

I tried to use useMemo hook but couldn't figure out how to use it. Any help?

Here is my code:

import React, { useEffect, useState } from 'react';
import { Map, TileLayer, Marker, Popup } from 'react-leaflet';
import axios from 'axios';
import { v4 as uuidv4 } from 'uuid';
import { Icon } from 'leaflet';

const myicon = new Icon({
  iconUrl: './icon.svg',
  iconSize: [20, 20]
});

const MyMap = () => {
  const [myState, setMyState] = useState(null);
  const [activePlace, setActivePlace] = useState(null);

  const getData = async () => {
    let response = await axios
      .get('https://corona.lmao.ninja/v2/jhucsse')
      .catch(err => console.log(err));

    let data = response.data;
    setMyState(data);

    // console.log(data);
  };

  useEffect(() => {
    getData();
  }, []);

  if (myState) {
    console.log(myState);
    return (
        <Map
          style={{ height: '100vh', width: '100vw' }}
          center={[14.561, 17.102]}
          zoom={1}
        >
          <TileLayer
            attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors &copy; <a href="https://carto.com/attributions">CARTO</a>'
            url={
              'https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png'
            }
          />

          {myState.map(country => {
            return (
              <Marker
                key={uuidv4()}
                position={[
                  country.coordinates.latitude,
                  country.coordinates.longitude
                ]}
                onmouseover={() => {
                  setActivePlace(country);
                }}
                onmouseout={() => {
                  setActivePlace(null);
                }}
                icon={myicon}
              />
            );
          })}

          {activePlace && (
            <Popup
              position={[
                activePlace.coordinates.latitude,
                activePlace.coordinates.longitude
              ]}
            >
              <div>
                <h4>Country: {activePlace.country}</h4>
              </div>
            </Popup>
          )}
        </Map>
    );
  } else {
    return <div>Loading</div>;
  }
};

export default MyMap;

m00
  • 297
  • 1
  • 5
  • 13
  • Have you already tried to use Pure Component or you need to use a stateless component to keep the react hooks? – Victor Alessander Mar 29 '20 at 02:43
  • @VictorAlessander I haven't tried pure component. I don't understand the next part you're saying. – m00 Mar 29 '20 at 02:51
  • Stateless component is also called as function component (https://reactjs.org/docs/components-and-props.html#function-and-class-components) – Victor Alessander Mar 29 '20 at 02:58
  • @VictorAlessander is there a way to fix it while keeping it a functional component, i don't want to use class based components – m00 Mar 29 '20 at 03:00
  • 1
    Just because this function is re-running when state changes, does not mean the UI is re-rendering. is this causing a problem in your application, or are you just concerned because you think that it might do? – JMadelaine Mar 29 '20 at 03:33
  • @JMadelaine yeah it's causing my markers on the map to flicker every time the popup opens up and it's making the map feel laggy too compared to when i disable the popups – m00 Mar 29 '20 at 03:36
  • I've added an answer, your issue is because you're assigning random IDs, which defeats the point of having IDs in the first place. – JMadelaine Mar 29 '20 at 03:41

1 Answers1

5

This line is your problem:

key={uuidv4()}

Why are you creating a unique ID on every render? The point of an ID is that it stays the same between renders so that React knows that it doesn't have to re-draw that component in the DOM.

There are two stages that happen whenever state changes, the render phase and the commit phase.

The render phase happens first, and this is where all of your components execute their render functions (which is the entire component in the case of a function component). The JSX that is returned is turned into DOM nodes and added to the virtual DOM. This is very efficient and is NOT the same as re-rendering the actual DOM.

In the commit phase, the new virtual DOM is compared to the real DOM, and any differences found in the real DOM will be re-rendered.

The point of React is to limit the re-renders of the real DOM. It is not to limit the recalculation of the virtual DOM.

This means that it is totally fine fine for this entire component to run its render cycle when activePlace changes.

However, because you're giving a brand new ID to each country on every render cycle, the virtual DOM thinks that every country has changed (it uses IDs to compare previous DOM values), so all the countries in the actual DOM also get re-rendered, which is probably why you're seeing issues with lag.

The ID should be something related to the country, e.g. a country code, not just a random UUID. If you do use random UUIDs, save them with the country so that the same one is always used.

JMadelaine
  • 2,859
  • 1
  • 12
  • 17
  • That makes so much sense. Thank you so much!!! my map is now really smooth and the flickering of markers has stopped. Can you tell me this one last thing that why the `console.log(myState)` is still running every time popup opens/closes? – m00 Mar 29 '20 at 04:27
  • 1
    The console.log will run every time the render phase happens, and the render phase happens every time component state changes. There's nothing to worry about. This is expected behaviour. – JMadelaine Mar 29 '20 at 04:30
  • Oh ok. Thank you once again, these markers were freaking me out. – m00 Mar 29 '20 at 04:45