saasquatch/bunshi

Garbage collection of Molecules.

suman379 opened this issue · 4 comments

I have created a molecule and used with Scope provider.

  1. Screen mounted, then I changed the state of atom.
  2. I went to the previous screen(Screen unmounted).
  3. Again I opened the same screen from step 1, But It still hold the changed state not the initial state.

Is there any way to reset the molecules/garbage collection?

Is this lib maintained anymore?
I was wondering the same thing :/

Hey @suman379 thanks for the question.

What you are describing is a feature of the library. Molecules are lazy and exist for their entire scope. The solution that you are looking for is to use scoping.

A global molecule will always return the same value

// Will always return the same number, because this molecule is globally scoped
molecule(()=>Math.random());

If you want a different value for a particular page, section, form, user, company, or other lifetime, then you should use scopes and a scoped molecule.

const pageScope = createScope<string>();

// Will produce a random number for every page scope
const randomPerPage = molecule((_,scope)=>{
    const currentPage = scope(pageScope);
    const num = Math.random();
    return {
      currentPage,
      num
   }
});

Then in your components, use your pageScope with a ScopeProvider.

<ScopeProvider scope={pageScope} value="home">
   <InnerComponentThatUsesMolecule/>
</ScopeProvider>

Does this answer your question?

Sorry for the delay in the response @Brian-McBride and @suman379

There is a new capability in Bunshi 2.1.0 around lifecycles, see the docs: https://www.bunshi.org/concepts/lifecycle/

You can use onMount and onUmount to handle side-effects when your molecules are mounted and unmounted.

For example, this capability was used to fix a memory leak in the XState example #36

@suman379 I'm closing this as an issue, I believe the intended behavior is well covered by tests.

For general suggestions and questions, please open a discussion.