skip to Main Content

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


  1. 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)

    Login or Signup to reply.
  2. you can try :

    // Server-side code
    const seed = 'your seed value'; // Set a fixed seed value
    const randomArray = [...yourArray]; // Create a copy of your array
    
    // Function to shuffle the array using the Fisher-Yates shuffle algorithm
    function shuffleArray(array) {
      for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
      }
    }
    
    // Seed the random number generator
    Math.seed = seed;
    
    // Shuffle the array using the seeded random number generator
    shuffleArray(randomArray);
    
    // Send the randomized array to the client-side as part of the response
    res.send({ randomArray });
    //Client Side
    
    import React, { useEffect, useState } from 'react';
    
    // Assume you received the randomized array from the server as `randomArray`
    
    const YourComponent = () => {
      const [shuffledArray, setShuffledArray] = useState([]);
    
      useEffect(() => {
        setShuffledArray(randomArray);
      }, []);
    
      // Render the component with the shuffledArray
      return (
        <div>
          {/* Use the shuffledArray in your UI */}
          {shuffledArray.map((item, index) => (
            <p key={index}>{item}</p>
          ))}
        </div>
      );
    };
    
    export default YourComponent;

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search