A handy react hook to get a random value from an array without repeating the most recent value.
Pass in the desired values
const { currentValue, shuffleValues } = useShuffleValues([
"purple",
"orange",
"green",
"pink",
"red",
"blue",
"yellow",
]);
Use the returned currentValue in your component
<Box
bg={currentValue}
>
Hi, I'm a Box
</Box>
Call the shuffle function to get the next value
const someFunction = () => {
shuffleValues();
}
On our agency website, Complerity.ch we use the hook on several pages.
We style the links with the returned currentValue and call the shuffleValues function onMouseLeave:
224546922-6a257dc5-ef4a-4190-aa0c-7548d161fc74.mp4
We style the menu layer with the returned currentValue and call the shuffleValues function in a gsap timeline callback:
224547163-195d5798-4bac-4cd2-8ac8-6482f1a435ac.mp4
If you want to get a value more over another, just pass in the desired value multiple times.
Please note that we're using a do-while loop to obtain the new value, which can lead to suboptimal performance when dealing with many duplicates.
To filter the array beforehand, change the shuffleValues
function to the following:
//…
const shuffleValues = () => {
setCurrentValue((prevValue) => {
let filteredValues = [];
for (let i = 0; i < values.length; i++) {
if (values[i] !== prevValue) {
filteredValues.push(values[i]);
}
}
return getRandomValue(filteredValues);
});
};
//…