Tips for handling global state within a library

Does anyone have any tips for handling global state. By global I mean state that persists between function invocations. I’m developing a library that exposes an authenticate(): Promise<Principal> function, behind the scenes authenticate is implemented as an effect. The function performs some expensive operations that I’d like to cache and I’ve been looking at caching options.

Caching operations within authenticate is easy, I can just create a cache and provide it where needed, but having a cache that sits above the function is more difficult, without shifting responsibility onto the caller of that function.

I’m thinking of wrapping the function in a class with its own make function that would construct the cache and store it as an instance variable. I don’t really like the pattern as callers need to wait for the class to be initialised before they can call functions and classes make tree shaking more difficult.

Any better ideas?
Was this page helpful?