Creating custom SolidJS hook that can be used in a global scope

Need some help understanding how to build a custom SolidJS hook that can be used both locally inside a component and outside in the global scope (like createSignal can). Below is. a small snippet of a custom hook I am writing:
export function createDatabase(dbOrName?: string | Database, config: ConfigOpts = {}): CreateDatabase {

const database = createMemo(() => (isDatabase(dbOrName) ? dbOrName : genDb(dbOrName || "DefaultDB", config)));

return { database }
export function createDatabase(dbOrName?: string | Database, config: ConfigOpts = {}): CreateDatabase {

const database = createMemo(() => (isDatabase(dbOrName) ? dbOrName : genDb(dbOrName || "DefaultDB", config)));

return { database }
The question I have is around the floating createMemo that I use in the implementation. When I use the createDatabase hook globally, I get greeted with the console warning: computations created outside a 'createRoot' or 'render' will never be disposed I'm not familiar with how to properly address that warning and hoping the community can offer some guidance here.
10 Replies
Brendonovich
Brendonovich6mo ago
This part of the tutorial should help: https://www.solidjs.com/tutorial/stores_nocontext
SolidJS
Solid is a purely reactive library. It was designed from the ground up with a reactive core. It's influenced by reactive principles developed by previous libraries.
Brendonovich
Brendonovich6mo ago
Namely wrap your memo in createRoot
MaveriX89
MaveriX896mo ago
Ah, excellent. It's either that or I wrap the entire export of my function in a createRoot is another option as well correct?
Brendonovich
Brendonovich6mo ago
Yeah that's also an option Ah actually maybe no As long as the createMemo is inside the createRoot you can do whatever else you want
MaveriX89
MaveriX896mo ago
Gotcha -- so it seems I can take one of those two approaches. Really appreciate the insight!! Thank you!
Brendonovich
Brendonovich6mo ago
No worries, all you're really doing is silencing the warning The createMemo will still never be disposed since you don't manually dispose the root But that's your intended behaviour
MaveriX89
MaveriX896mo ago
Are there any potential downside to use hooks in a global manner for SPAs?
Brendonovich
Brendonovich6mo ago
Not that I'm aware of Testability may be one
MaveriX89
MaveriX896mo ago
Ah, yeah, I can see that becoming a problem for sure Good call
Alex Lohr
Alex Lohr6mo ago
We have renderHook in @solidjs/testing-library, so testability should be covered.
Want results from more Discord servers?
Add your server
More Posts