Next.js Discord

Discord Forum

singleton pattern with global in RSC is not supporting?

Unanswered
Asian black bear posted this in #help-forum
Open in Discord
Avatar
Asian black bearOP
While using the redis client as a singleton pattern to check the session in the rsc layout, the connection continuously occurred, so I checked it.

in those test code, why globalForTest.test values resetted to undefined?

is it bug? or am i doing something wrong?
Image
Image

22 Replies

Avatar
Asian black bearOP
ok when i check it's call seq, testSingleton called twice.

why it called again after rendered? 🤔

(0 => 1): testSingleton => (2): layout => (0 => 1): testSingleton
Image
Image
Image
Avatar
how are you doing the test?
Avatar
Asian black bearOP
just with
next dev + app dir
Avatar
and are those just froma single request or multiple requests
Avatar
Asian black bearOP
just for every request, testSingleton sequence called twice
Avatar
can i show you how i set up my singleton?
Avatar
Asian black bearOP
sure! i'll test again with that method
this log for single request
Avatar
I called it everywhere on the page so it should show up more than 2, but here it only show up once or twice
ideally every request should show up once only
but it might be inconsistencies with dev server. one should try in prod
Image
Avatar
Asian black bearOP
Is it a correct for notion client to be created on every request?
Avatar
Im deploying it on Vercel so it has to be stateless. yes
if you deploy it on non-serverless architecture, i believe you could just make global exports normally lol
i.e nothing can persists between requests
Avatar
Asian black bearOP
even is it with non-serverless?
Avatar
Vercel is serverless so no, that doesn't apply
Avatar
Asian black bearOP
In prod it works as expected.
In dev, keep got "The server is running out of memory, restarting to free up memory", it's why i dig this stuff.
maybe this is causing a memory leak in the dev. (Importing twice in rsc?)
I will debug heap and check second import is disposed. if not i will write a gh issue for it.
thank you!
Image
Avatar
No problem!
Avatar
Asian black bearOP
do you know why it behaves like that?
I'd like to know if this is the intended implementation.