Skip to content

Instantly share code, notes, and snippets.

@knjname
Last active February 9, 2021 16:07
Show Gist options
  • Save knjname/5ad277f684464419d171dd58026df6cc to your computer and use it in GitHub Desktop.
Save knjname/5ad277f684464419d171dd58026df6cc to your computer and use it in GitHub Desktop.
A react hook for mobx-state-tree that preserves the last state when reloading
import { getSnapshot, Instance } from "mobx-state-tree";
import { createContext, useEffect, useState } from "react";
import { MyStore } from "./MyStore";
export const useMyStore = () => {
const [state, setState] = useState(() => MyStore.create());
useEffect(() => {
if ((window as any).reentrant) {
const newState = MyStore.create(getSnapshot(state));
setState(newState);
}
return () => {
(window as any).reentrant = true;
};
}, []);
return state;
};
export const MyStoreContext = createContext<Instance<typeof MyStore>>(
undefined as any
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment