Next.js Discord

Discord Forum

Math.random() inconsistent between server and client

Unanswered
American Crow posted this in #help-forum
Open in Discord
American CrowOP
I'm trying to make a skeleton with a random width while real data is loading, but the client and the server obviously do not share the same Math.random(), so they give different widths.
How can I implement these skeletons with random width in a way that doesn't break SSR?
I've thought about useId, but it gives me a string and I don't think taking a hash of that would be the simplest way, nor fastest, is there some other way?

11 Replies

American CrowOP
I have googled for this a lot and seems no one else is trying to do what I am doing, or they are not having issues with it
You could make an inline CSS with using nth props and then have random widths (this way it should be ssrd and client doesn't recompute)
@American Crow I'm trying to make a skeleton with a random width while real data is loading, but the client and the server obviously do not share the same Math.random(), so they give different widths. How can I implement these skeletons with random width in a way that doesn't break SSR? I've thought about useId, but it gives me a string and I don't think taking a hash of that would be the simplest way, nor fastest, is there some other way?
I would just pick out some random numbers and hardcode them. Same width for all requests. It’s just a skeleton anyway.

But if you want Math.random(): you need a seeded random number generator. Grab one for yourself, and set the same seed for both the server invocation and the client one.
But I guess its not awful to just hardcode it
As an example, discord's "loading messages" skeleton has random widths every time
I rhink discords is set
Just lots of variations to appear random
@riský Just lots of variations to appear random
American CrowOP
Its possible I did not pay enough attention
Thank you either way :)
Random ™️