In this project i have used Solidjs Context for global state management. Context helps to pass signal and store reactive data to nested components without relaying on props drilling.
You can easily create context and use in components and pages where needed.
import{createContext,useContext}from"solid-js";import{createStore}from"solid-js/store";//context for manage stateconstMyContextState=createContext();//context containing method that will update reactive state dataconstMyContextDispatch=createContext();constinitialState={// your reactive data initial values comes here...};exportdefaultfunctionMyProvider(props){const[store,setStore]=createStore(initialState);constmyMethod1=()=>{// update store value using setStore()};return (<MyContextState.Providervalue={store}><MyContextDispatch.Providervalue={{myMethod1,// so on...}}>{props.children}</MyContextDispatch.Provider>
</MyContextState.Provider>
);}exportconstuseMyState=()=>useContext(MyContextState);exportconstuseMyDispatch=()=>useContext(MyContextDispatch);
Inside your components you can import useMyState and useMyDispatch
Auth context keeps reactive data related to authentication, user details and account. It also manage socket instance when someone successfully authenticated.
socket and manage keeps socket.io client related data.
onMount i fetch current user data using jwt token . If it success then i update store data otherwise i redirect to login screen.
Notification context
Notification context track notifications count and data . It use socket.io client to fetch realtime notification from server and update store. After that Notification component at Navbar update notification count and data.
My Notification context initial data looks like this
constinitialState={count:0,notifications:[],};
UI Context
Ui context keeps track of ui related data like snackbars.
Messenger context
Messenger context keeps track of friends and active chat related data.
Do not make context global when it is not required
I have only those context in global which is required. For example i added auth , notification and ui context global but messenger context is only needed by my messenger route and hence i only scoped messenger context inside messenger route. In this way we can add less weight on top of page.
In my next post i will write about how i used hooks in my application.