N
Nuxt4mo ago
rtrap

Composable and Cross-Request State pollution

The documentation here https://nuxt.com/docs/getting-started/state-management#best-practices tell to not define a ref outside setup and it suggest to use the useState composable. Question: If I write a composable that defines a state with ref at the root of the module, and I use this composable only in the setup of components, shouldn't it be re-executed on every request (and thus avoid pollution issues)?
Nuxt
State Management · Get Started with Nuxt
Nuxt provides powerful state management libraries and the useState composable to create a reactive and SSR-friendly shared state.
1 Reply
Cue
Cue4mo ago
Technically, yes. However, during SSR, your app is rendered once for all SSR requests. So long as you’re not doing atypical state management, rather storing something like a boolean that changes when, for example, a hook determines the hydration state has changed; something not impacted by user behaviour or environment, it should be fine. The reason it is discouraged is to encourage state isolation. Many people will see it as “it’s fine, everything works, so I’ll keep throwing all my data in it”. This leads to memory leaks and global state can be difficult to trace and debug, hence there is dedicated utils, such as useState, made available to you. Other edge cases also include test driven development where isolated state makes for better tests without global state interference. Last but not least, memory leaks are a real thing. Many people wouldn't know where to start when it comes to tracing memory leaks, let alone know if such practices are causing leaks to begin with. Global refs, when created by a module, are kept alive so long as the module is alive. State inside a composable, however, is disposed of when the component itself is destroyed. Although there are cases where you may want to share state, it is always good practice to utilise useState to keep your project in good stead.
Want results from more Discord servers?
Add your server