Using a function outside of components
Hi all, I've come across an interesting situation. I am currently doing a project using SolidJS. I have a hook (hello React) that handles authentication:
There is also a generic site template that has a check if the user is authorized or not to show the right menu items:
And also the login page itself which calls the login method:
So, the problem is that the state seems to change internally, but is not tracked externally (as if each component in which useAuth() is called has its own state of signals). I initially solved the problem by using createContext/useContext. Later I went to see if there is a state manager library for SolidJS, like Recoil for React. Not finding anything I decided to try to write a wrapper over createContext/useContext similar to Recoil. And what is interesting is that I accidentally noticed unusual behavior of createSingal, and in general all "hooks" in SolidJS. In React all useX functions (useState, useEffect, etc.) should be strictly used only in hooks, which is not the case in SolidJS. I.e. you can write the following code and it will work as it should:
I would like to know if this is considered normal practice in SolidJS, or should I not write this way to avoid bugs in the future?
4 Replies
Later I went to see if there is a state manager library for SolidJS, like Recoil for ReactSolid's equivalent to React's state management libraries is pretty much just signals and stores, they work wherever you need
I would like to know if this is considered normal practice in SolidJS, or should I not write this way to avoid bugs in the future?Nah it's fine, an example of using stores outside of components is actually part of the tutorial 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.
Wow, that's true. I should probably read the rest of the textbook.
yes 🙂 welcome to solid, reactivity everywhere
https://www.youtube.com/watch?v=cELFZQAMdhQ is a good introduction to the basic concept of how its reactivity (and signals in general) work
SolidJS
YouTube
Intro to SolidJS reactivity (in 5 minutes)
An introduction video that walks you through Solid's reactivity in under 5 minutes.