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

@firefox-pro-coding/react-composition-api

v1.0.0

Published

Writing react component with composition api

Downloads

3

Readme

react-composition-api

version license David David Coverage

Using React + Mobx with composition api style! 🙌

Using mobx + react, you can write React components in composition api with this lib. Zero dependency and less than 2kb gzip!

Install

# react 16.8 is required for hooks
# mobx and mobx-react-lite is required for reactivity
yarn add react mobx mobx-react-lite
yarn add @firefox-pro-coding/react-composition-api

Usage

const Component = defineComponent((props) => {
  const state = observable({ count: 1 })
  const add = action(() => { state.count += 1 })

  return () => (
    <div>
      hello world! {state.count}
      <button onClick={add}>add</button>
    </div>
  )
})

another counter example

Pass a setupFunction to defineComponent to create a Component.

setupFunction will run once per component and the render funtion it returns is used for rendering if any of it's dependencies changes.

props is a shallow reactive object for the props that the parent pass to it, you can use reaction to watch changes on props.

You can't use any react hooks directly in the setupFunction, as it will only run once. If any hooks are used, you will have problems about react complaining rendering fewer hooks etc.

Benefits

  • better component logic composition
  • setup only execute once, less gc pressure
  • little hooks involved, reduce some boilerplate

Babel Plugin

Normally, you need to tear down mobx reaction watchers when component unmounted. You can import these reactivity utilities wrappers from @firefox-pro-coding/react-composition-api, or use the babel plugin to transform imports from mobx to this package.

// using wrapper from @firefox-pro-coding/react-composition-api
import {
  observable,
  reaction,
  autorun,
  when,
} from '@firefox-pro-coding/react-composition-api'
// or using babel to auto transform
// .babelrc.js
module.exports = (api) => {
  api.cache.using(() => process.env.NODE_ENV)

  return {
    plugins: [
      '@firefox-pro-coding/react-composition-api/babel',
    ],
  }
}


// import from mobx
import { observable, autorun, when, reaction, observe } from 'mobx'
// will be transformed into
import { observe } from 'mobx'
import {
  observable,
  autorun,
  when,
  reaction,
} from '@firefox-pro-coding/react-composition-api'

Api Reference

  • defineComponent

    const Component = definedComponent((props) => () => {
      // props is shallow reactive
      // define your state actions in here
    
      // the render function used to render the component
      // will be wrapped in mobx.observer automatically
      return () => (
        <div>component</div>
      )
    })

    Pass a setupFunction to defineComponent to create a component. setupFunction should return a render function that receives no arguments and returns JSX.

    setupFunction receive props as it's argument. props is a stable reference and made shallow reactive, so you can use mobx reactions to watch changes on props.

  • observable, reaction, autorun, when
    These are wrappers of mobx api and do exactly the same thing as the same name in mobx, except when called inside the setupFunction synchronously, and will be automatically disposed when component unmount.

    Use the babel plugin to auto transform these imports from mobx to this package.

  • onMounted, onUnmounted

    onMounted(() => { console.log('mounted') })
    onUnmounted(() => { console.log('unmounted') })

    Life Cycle hooks when the component mounted and unmounted.

    Callback are wrapped in React.useEffect hook, so using onMounted and onUnmounted is the same as React.useEffect with an empty array as deps, except it's allowed to be used inside if statement, and the order doesn't matter.

    Reactions won't be auto torn down in life cycle hooks.

    Tips: You can call onUnmounted inside onMounted synchronously.

  • onUpdated

    onUpdated(() => { console.log('updated') })

    Life Cycle hooks when component render completes.

    onUpdated(cb)
    // basically same as
    React.useEffect(() => {
      cb()
    }, [])
  • runhook

    const state = observable({
      value: 0,
    })
    
    runHook(() => {
      const newValue = React.useContext(MyContext)
      state.value = newValue
    })

    Callback passes to runHook will run every time before the component renders, just like normal hooks. Regular hook rules applies here.

    To react to changes, modify the state inside the callback. Normal hooks rules apply here, so you cant call hooks inside if statement.

    What's the difference of runHook and onUpdated? You can think them of as this:

    const Component = () => {
      executeRunHook()
      React.useEffect(() => {
        executeOnUpdated()
      })
    }

Tips

Want to learn more about composition api? Check out vue composition api RFC https://vue-composition-api-rfc.netlify.app/

If you are using fast refresh in development, and wish states to preserve when component was changed and hot reloaded, all the states that preserve must be in a observable, because observable calls were cached when hot reload, and others were not.

const Component = defineComponent(() => {
  // rootRef will be a new ref with current as null when component hot reloaded
  const rootRef = React.createRef<HTMLDivElement>(),

  return () => (
    <div ref={rootRef}>root</div>
  )
})

const Component = defineComponent(() => {
  // state.rootRef will still be the same value as before hot reload
  const state = observable({
    rootRef: React.createRef<HTMLDivElement>(),
  }, { rootRef: observable.shallow })

  return () => (
    <div ref={state.rootRef}>root</div>
  )
})