javascriptsveltesveltekites6-modules

Is this object created only once or every time I import it?


Since I'm having a bug that I can't figure out, a cold doubt has assailed me:.

I have the below code in a Svelte 5 SvelteKit app.

And I'm importing import { queryClient } from './src/query.ts from multiple places in my big and complex app.

Doing so am I recreating queryClient each time I import it?

Or is it creating it only one time per app lifecycle?

Is there a way to call it just one time per lifecycle of the app?

export const queryClient = new QueryClient({
    defaultOptions: {
        // options here
    }
});

Solution

  • No, you are NOT recreating queryClient each time you import it.

    The very first time query.ts is imported anywhere in your application, the code inside query.ts is executed. This is when new QueryClient(...) is called, and the queryClient constant is initialized and assigned the new QueryClient instance. This instance is then stored in a module-level cache.

    For all subsequent imports of query.ts (from any other file in your application), the module system recognizes that query.ts has already been loaded and executed. Instead of re-executing the file, it simply returns the already-cached queryClient instance from the module cache.