Last active
January 13, 2023 07:20
-
-
Save jetako/2842c2f1854c887d198859ff9fdb2dab to your computer and use it in GitHub Desktop.
MobX-State-Tree Fast Refresh hook
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice ~