'Update array in react without causing a re-render
I have a React application with an animation based on an array. I need to display the array of elements in a circular motion but, at the same time, the elements need to be selected randomly with a probability weight.
The elements are something like:
const el = [
{
id: 1,
prob: 0.04,
flag: 'US',
text: 'whatever',
},
{
id: 2,
prob: 0.22,
flag: 'FR',
text: 'whatever',
},
...
]
I select the random element to display in the following way:
const interval = setInterval(() => {
let arrayOfProbabilities = filteredCountryByYear.flatMap(
(i) => i.prob
);
const testarray = [];
for (let i = 0; i < 24; i++) {
testarray.push(
weightedRandom(filteredCountryByYear, arrayOfProbabilities)
);
}
const globeSpinningCountriesClone = [...testarray];
globeSpinningCountriesClone.shift();
globeSpinningCountriesClone.push(
weightedRandom(filteredCountryByYear, arrayOfProbabilities)
);
setGlobeSpinningCountries(globeSpinningCountriesClone);
}, 2000);
return () => clearInterval(interval);
Basically I initialise the element with 24 random picked elements got from the weightedRandom function, since the animation requires to have always 24 elements displayed.
After that I shift the array (deleting the first element) and I push a new one.
The variable globeSpinningCountries is passed on the animation component as prop.
The problem is that whenever I update the array, the animation component re-render and the animation has a visual refresh and start from the beginning, I'd like the animation to keep going, just with a different element everytime.
This is the animation component:
<div tw="w-full h-full absolute animate-spin">
{globeSpinningCountries.map(({ file_url, sector }, i) => (
<>
<DynamicSvg
globeSpinningCountries={globeSpinningCountries}
i={i}
iconName={sector}
/>
<img
// key={i}
src={file_url}
css={[
tw`bottom-[50%] origin-[center bottom] absolute object-contain object-[0 0] h-[calc(62.125rem - 57%)] w-[1.56rem] left-[50%] md:w-[0.875rem] md:h-[calc(35.75rem - 57%)]`,
`transform: translate(-50%) ${calculateDegrees(
24,
i
)}`,
]}
alt="Country"
/>
</>
))}
</div>
This div display the elements around a globe and makes them rotate.
Is there a way to achieve this?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
