Skip to content

Latest commit

 

History

History
68 lines (56 loc) · 1.75 KB

README.md

File metadata and controls

68 lines (56 loc) · 1.75 KB

useShuffleValues 🎲

A handy react hook to get a random value from an array without repeating the most recent value.

How to use it

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();
}

Demo

On our agency website, Complerity.ch we use the hook on several pages.

Example 1

We style the links with the returned currentValue and call the shuffleValues function onMouseLeave:

224546922-6a257dc5-ef4a-4190-aa0c-7548d161fc74.mp4

Example 2

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

Balancing

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);
    });
};
//…