Last active
March 21, 2020 10:34
-
-
Save wickedev/dc2189c2b25b99433452cd9f30ad1049 to your computer and use it in GitHub Desktop.
MobXProviderContext sample
This file contains 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 { action, observable } from 'mobx' | |
import { MobXProviderContext, observer, Provider } from 'mobx-react' | |
import React, { useContext } from 'react' | |
class CounterViewModel { | |
@observable count: number = 0 | |
@action.bound public plus() { | |
this.count++ | |
} | |
@action.bound public minus() { | |
this.count-- | |
} | |
} | |
export function App() { | |
return ( | |
<Provider counter={new CounterViewModel()}> | |
<Counter /> | |
</Provider> | |
) | |
} | |
const Counter = observer(() => { | |
const { counter }: { counter: CounterViewModel } = useContext( | |
MobXProviderContext, | |
) | |
return ( | |
<div> | |
<div>{counter.count}</div> | |
<button onClick={counter.minus}>-</button> | |
<button onClick={counter.plus}>+</button> | |
</div> | |
) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@jaeyow If you want to introduce mobx for the first time, you don't have to care about the legacy mobx-react Provider. It was because of the performance problem that react team removed the legacy Context from core and introduced the new Context API. MobXProviderContext is an effort by mobx maintainers to ensure backward compatibility while using the Context API internally.