简体   繁体   中英

How to stop react re-rendering component, if part of the state changes?

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;

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, eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM