Search code examples
reactjsserver-side-renderingmobxmobx-react

React SSR with nested Mobx stores


It is possible make ssr app with nested mobx stores? Problem is how serialize root store and restore it?

Example of my stores:

export default class RootStore {
     session = new SessionStore(this);
     ui = new UIStore();
}

export default class SessionStore {
    serverActionChecking = new ActionStore(this);
}

Solution

  • If you are referring to the process of rendering content on the server, and then hydrating the same stores in the frontend (like Next.js), you could do something like this:

    You could have a special function that creates your root store and depending on if the function is called with or without data, it calls the root store hydration method. Then the root store, after instantiation of the child stores, calls their hydration methods. Hydration data should be an object that has keys that correspond to the child stores, so you could just pass specific keys to specific stores.

    function initializeStore(initialData ) {
      const store = new RootStore();
    
      if (initialData) {
        store.hydrate(initialData);
      }
    
      return store;
    }
    
    
    class RootStore {
      hydrate(data) {
        if(data.childStoreOne){
          this.childStoreOne.hydrate(data.childStoreOne);
        }
      }
    }
    
    class ChildStoreOne{
      hydrate(data){
        //do something with the data
      }
    }
    

    Now all that is left to do is to get the hydration data to the browser. One of the solutions is to embed the data in the script tag and pass it to the initialization function.