npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

use-mobx-observable

v1.1.0-beta.1

Published

Using mobx observable with react hooks

Downloads

39

Readme

use-mobx-observable

npm version pages-build-deployment npm Coverage Status

Use mobx observable like useState

Note:

Install

npm install mobx@^6 react@^16.8 # peer dependencies
npm install use-mobx-observable

👉API Docs👈

Problem

The current mobx hooks from mobx-react-lite uses pattern like below:

function MyComponent() {

  let store = useLocalObservable(() => ({ count: 0 }))

  return (
    <Observer>                      // <---
    {                               // <---
      () =>                         // <---
        <div>{store.count}</div>
    }                               // <---
    </Observer>                     // <---
  )
}

To be reactive, you have to wrap your jsx with <Observer> and use render props, which is not a favorable way.

There was a Discussion around this issue. At the end of it, simple solution was proposed:

function useSelector(select) {
  const [selected, setSelected] = useState(select)
  useEffect(() => autorun(() => setSelected(select())), [])
  return selected
}

function myComponent({ observableOrder }) {
  const latestPrice = useSelector(() => observableOrder.price)
  return <h1>{latestPrice}</h1>
}

However, in practice, you'll still need to create an observable for computed and actions.

Do it at once

import { useObservable, select, useMultiObservables } from 'use-mobx-observable'

function MyComponent() {

  // create local observable, with plain object or an initializer
  let store = useObservable({
      count: 0,
      get countText() {
        return `Count: ${this.count}`
      },
      add() {
        this.count += 1
      },
    })

  // map external observable props to getters
  let store2 = useObservable(select(externalStore, ['propsA', 'propsB'])({ count: 0 }/* Optional */))

  // chaining with lodash.flow for mapping multiple sources
  let store3 = useObservable(
    _.flow(
      select(externalStore, ['propsA', 'propsB'],
      select(externalStore2, { renameC: 'propsC' },  // rename getters
    )({
      get sum() {
        return this.propsA + this.renameC
      }
     })
  )

  // use observable directly, returned value can be omitted since it is the same as input
  // Be ware of the performance impact: any props change will trigger a rerender.
  useObservable(store)

  return (
    <div>
      <h1>{store.countText}</h1>
      <button onClick={() => store.add()}>Add</button>
    </div>
  )
}

Automatically wrap observer HOC

Since React 17, jsx transformation is done via react/run-time instead of React.createElement. Typescript 4.1 introduced new jsx options which enabled customized jsx factory.

Hence, automatically wrap all your components with observer can be easily done via change your tsconfig.json:

{
  "compilerOptions": {
    "target": "esnext",
    "module": "commonjs",
    "jsx": "react-jsx",
    "jsxImportSource": "use-mobx-observable"
  }
}

If you choose this way, please remember install mobx-react-lite. Check auto-wrap-observer/wrap-jsx.js for detail.

Performance Impact?

TLDR; No, nothing you should worry about