ngrx / platform

Reactive State for Angular
https://ngrx.io
Other
8.01k stars 1.97k forks source link

Facilitate Garbage Collection with weak refs in Angular Universal / SSR #4513

Open amakhrov opened 1 month ago

amakhrov commented 1 month ago

Which @ngrx/* package(s) are relevant/related to the feature request?

store

Information

createSelector uses a memoization function under the hood that stores the reference to the last argument (state object). This works great in a browser, where there is a single global NgRx state per app. On the server (server rendering with Angular Universal), we get a new instance of the store, and a new instance of the global state for each user request.

It has two implications

This feature request is primarily concerned with the second item - multiple state instances that are not GC'd between the requests.

The suggested solution would involve using weak refs to store the last argument of a memoized selector. Furthermore, with weak refs we could store more that one last argument in the cache (via WeakMap) - thus also addressing my first bullet point from the above (should be careful with selectors args that are primitives though).

Describe any alternatives/workarounds you're currently using

None so far.

Theoretically, we could use createSelectorFactory (with a typing workaround because of https://github.com/ngrx/platform/issues/3987). But it means we need to update all selectors across the app. There is no way to override the default memoize function globally in the app.

I would be willing to submit a PR to fix this issue