I want to randomize an array of objects in server that matches in the client. I’ve tried to solve it using a state, useMemo hook… and the thing is that client and server never match.
For example, this code rendered in server is different from the one after hydration in client:
const myArray = [{
id: 1,
}, {
id: 2,
}, {
id: 3,
}];
// ........
export default function Component(myArray) {
const [randomized] = React.useState(suffleArray(myArray));
React.useEffect(() => {
trackValues(randomized);
}, [])
return (
<div>
{
randomized.map(({ id }) => id)
}
</div>
);
}
The important thing here is that I want a different order in each page load, but the HTML returned must be the same in both server and client.
2
Answers
I don’t think you can achieve the same order of randomization in two different machines at the same time.
if you want to achieve this you have to create your own randomization function which runs based on a key(which should be available in both servers)
you can try :
Seed the random number generator: Start by seeding the random number generator on both the server and client using the same value. This will ensure that they generate the same sequence of random numbers. For example, you can use a fixed seed value like Math.seed = ‘your seed value’;.
Generate a random order on the server: On the server side, randomize the array of objects using the seeded random number generator. You can use a shuffling algorithm like the Fisher-Yates shuffle. Make sure to use the same seed value you set in step 1.
Send the randomized array to the client: Once you have the randomized array on the server, send it to the client-side as part of the response.
Use the randomized array on the client: On the client side, use the received randomized array to populate your UI or perform any required operations. Ensure that you’re not re-randomizing the array on the client-side.