For reference: https://en.wikipedia.org/wiki/Wikipedia:Lists_of_common_misspellings/For_machines
3.3 KiB
MobX example
Usually splitting your app state into pages
feels natural but sometimes you'll want to have global state for your app. This is an example on how you can use MobX that also works with our universal rendering approach. This is just a way you can do it but it's not the only one.
In this example we are going to display a digital clock that updates every second. The first render is happening in the server and then the browser will take over. To illustrate this, the server rendered clock will have a different background color than the client one.
This example is a mobx-react-lite port of the with-mobx example. MobX support has been implemented using React Hooks.
Deploy your own
Deploy the example using Vercel:
How to use
Using create-next-app
Execute create-next-app
with npm or Yarn to bootstrap the example:
npx create-next-app --example with-mobx-react-lite with-mobx-react-lite-app
# or
yarn create next-app --example with-mobx-react-lite with-mobx-react-lite-app
Download manually
Download the example:
curl https://codeload.github.com/vercel/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-mobx-react-lite
cd with-mobx-react-lite
Install it and run:
npm install
npm run dev
# or
yarn
yarn dev
Deploy it to the cloud with Vercel (Documentation).
Implementation details
The initial store data is returned from the initializeData
function that recycles existing store data if it already exists.
function initializeData(initialData = store || {}) {
const { lastUpdate = Date.now(), light } = initialData
return {
lastUpdate,
light: Boolean(light),
}
}
The observable store is created in a function component by passing a plain JavaScript object to the useObservable
hook. Actions on the observable store (start
and stop
) are created in the same scope as the store
in store.js
and exported as named exports.
store = useObservable(initializeData(props.initialData))
start = useCallback(
action(() => {
// Async operation that mutates the store
})
)
stop = () => {
// Does not mutate the store
}
The component creates and exports a new React context provider that will make the store accessible to all of its descendents.
return <StoreContext.Provider value={store}>{children}</StoreContext.Provider>
The store is accessible at any depth by using the StoreContext
.
const store = useContext(StoreContext)
The clock, under components/Clock.js
, reacts to changes in the observable store
by means of the useObserver
hook.
return (
<div>
// ...
{useObserver(() => (
<Clock lastUpdate={store.lastUpdate} light={store.light} />
))}
// ...
</div>
)