admin管理员组文章数量:1432352
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='© <a href="">OpenStreetMap</a> contributors © <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='© <a href="https://www.openstreetmap/copyright">OpenStreetMap</a> contributors © <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
1 Answer
Reset to default 5This 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.
本文标签: javascriptHow to stop react rerendering componentif part of the state changesStack Overflow
版权声明:本文标题:javascript - How to stop react re-rendering component, if part of the state changes? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745602400a2665643.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论