I have this problem where every time a user hovers there mouse pointer over my map of the USA, the map renders again. (Visually, it flashes on the screen and it looks terrible).
This is because I have an 'entityRolloever' event which causes a state variable to change.
entityRollover: function(event, data){
setHoveredState(data.label)
}
How I understand it is, when a React component (i.e. my map) changes state, it re-renders.
But what I want is, when a user hovers over a U.S. State, I want the state that is being hovered over to show up in a separate text box (without the whole map re-rendering).
I have searched around, and I have found some other React hooks which could solve this. They are useRef, useMemo, and useCallback. However, I'm not sure how they would solve my problem as I have never used them before.
If you want to recreate my problem, create a basic React app
npx create-react-app
Install the following packages
npm i fusioncharts react-fusioncharts fusionmaps
Then grab the code in my jsfiddle and paste it into 'App.js'
There are a couple of ways to resolve this issue. I chose to replace
useState()hook withuseRef()since it matches your case perfectly.useState()is a hook used in functional components to re-render components on state change, but in your case this is NOT something that we want. We want to track the updates without re-rendering the components. To achieve this, we useuseRef(). When we useuseRef()for the updates it will not fire re-rendering unlikeuseState().In your code, I commented out the
{hoveredState}you had to avoid re-rendering. Then I created apelement andrefit withuseRef(). Then on theentityRollovemethod, I update theinnerTextof the referencedpelement. This way we are tracking the updates without re-rendering. It is simpler to see the code, I did comment on the lines I added: (paste it in your App.js)