Skip to content

Instantly share code, notes, and snippets.

@jetako
Last active January 13, 2023 07:20
Show Gist options
  • Save jetako/2842c2f1854c887d198859ff9fdb2dab to your computer and use it in GitHub Desktop.
Save jetako/2842c2f1854c887d198859ff9fdb2dab to your computer and use it in GitHub Desktop.
MobX-State-Tree Fast Refresh hook
import { useRef } from 'react'
import { applySnapshot, getSnapshot, IStateTreeNode } from 'mobx-state-tree'
/**
* Preserves state when fast refresh causes the root store to change.
*/
export function useMSTFastRefresh(rootStore: IStateTreeNode) {
const rootStoreRef = useRef(rootStore)
if (rootStore !== rootStoreRef.current) {
console.log('Root store changed. Applying previous snapshot.')
const snapshot = getSnapshot(rootStoreRef.current)
try {
applySnapshot(rootStore, snapshot)
} catch (error) {
console.log(`Failed to apply previous snapshot: ${error}`)
}
rootStoreRef.current = rootStore
}
}
//------------------------------- Usage -------------------------------//
/**
* Add the useMSTFastRefresh() hook where you create the root store
*/
export const App = ({ rootStore = RootStore.create() }) => {
useMSTFastRefresh(rootStore)
return (
<StoreProvider value={rootStore}>
<Root />
</StoreProvider>
)
}
@lazyunderscore
Copy link

Nice ~

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment