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

Is there a way to stop react re-rendering if only part of state changes?The problem is that every time

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('/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="">OpenStreetMap</a> contributors &copy; <a href="">CARTO</a>'
            url={
              'https://{s}.basemaps.cartocdn/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;

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/copyright">OpenStreetMap</a> contributors &copy; <a href="https://carto./attributions">CARTO</a>'
            url={
              'https://{s}.basemaps.cartocdn./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;

Share Improve this question asked Mar 29, 2020 at 2:04 m00m00 3171 gold badge6 silver badges13 bronze badges 7
  • Have you already tried to use Pure Component or you need to use a stateless ponent to keep the react hooks? – Victor Alessander Commented Mar 29, 2020 at 2:43
  • @VictorAlessander I haven't tried pure ponent. I don't understand the next part you're saying. – m00 Commented Mar 29, 2020 at 2:51
  • Stateless ponent is also called as function ponent (reactjs/docs/…) – Victor Alessander Commented Mar 29, 2020 at 2:58
  • @VictorAlessander is there a way to fix it while keeping it a functional ponent, i don't want to use class based ponents – m00 Commented Mar 29, 2020 at 3: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 Commented Mar 29, 2020 at 3:33
 |  Show 2 more ments

1 Answer 1

Reset to default 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 ponent in the DOM.

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

The render phase happens first, and this is where all of your ponents execute their render functions (which is the entire ponent in the case of a function ponent). 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 mit phase, the new virtual DOM is pared 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 ponent 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 pare 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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745602401a4635478.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信