MCPcopy Index your code
hub / github.com/byte-fe/react-model

github.com/byte-fe/react-model @v4.2.1

Chat with this repo
repository ↗ · DeepWiki ↗ · release v4.2.1 ↗ · + Follow
70 symbols 271 edges 52 files 0 documented · 0% 1 cross-repo links
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

react-model · GitHub license npm version minified size Build Status size downloads Coverage Status Greenkeeper badge PRs Welcome

The State management library for React

🎉 Support Both Class and Hooks Api

⚛️ Support preact, react-native and Next.js

⚔ Full TypeScript Support

📦 Built with microbundle

⚙️ Middleware Pipline ( redux-devtools support ... )

☂️ 100% test coverage, safe on production

🐛 Debug easily on test environment

import { useModel, createStore } from 'react-model'

// define model
const useTodo = () => {
  const [items, setItems] = useModel(['Install react-model', 'Read github docs', 'Build App'])
  return { items, setItems }
}

// Model Register
const { useStore } = createStore(Todo)

const App = () => {
  return <TodoList />
}

const TodoList = () => {
  const { items, setItems } = useStore()
  return 


    <Addon handler={setItems} />
    {state.items.map((item, index) => (<Todo key={index} item={item} />))}



}

Recently Updated

Quick Start

createStore + useModel

CodeSandbox: TodoMVC

Next.js + react-model work around

v2 docs

install package

npm install react-model

Table of Contents

Core Concept

createStore

You can create a shared / local store by createStore api.

Online Demo

model/counter.ts

import { useState } from 'react'
import { useModel } from 'react-model'
const { useStore } = createStore(() => {
  const [localCount, setLocalCount] = useState(1) // Local State, Independent in different components
  const [count, setCount] = useModel(1) // Global State, the value is the same in different components
  const incLocal = () => {
    setLocalCount(localCount + 1)
  }
  const inc = () => {
    setCount(c => c + 1)
  }
  return { count, localCount, incLocal, inc }
})

export default useStore

page/counter-1.tsx

import useSharedCounter from 'models/global-counter'
const Page = () => {
  const { count, localCount, inc, incLocal } = useStore()
  return 


    <span>count: { count }</span>
    <span>localCount: { localCount }</span>
    <button onClick={inc}>inc</button>
    <button onClick={incLocal}>incLocal</button>



}

Model

Every model has its own state and actions.

const initialState = {
  counter: 0,
  light: false,
  response: {}
}

interface StateType {
  counter: number
  light: boolean
  response: {
    code?: number
    message?: string
  }
}

interface ActionsParamType {
  increment: number
  openLight: undefined
  get: undefined
} // You only need to tag the type of params here !

const model: ModelType<StateType, ActionsParamType> = {
  actions: {
    increment: async (payload, { state }) => {
      return {
        counter: state.counter + (payload || 1)
      }
    },
    openLight: async (_, { state, actions }) => {
      await actions.increment(1) // You can use other actions within the model
      await actions.get() // support async functions (block actions)
      actions.get()
      await actions.increment(1) // + 1
      await actions.increment(1) // + 2
      await actions.increment(1) // + 3 as expected !
      return { light: !state.light }
    },
    get: async () => {
      await new Promise((resolve, reject) =>
        setTimeout(() => {
          resolve()
        }, 3000)
      )
      return {
        response: {
          code: 200,
          message: `${new Date().toLocaleString()} open light success`
        }
      }
    }
  },
  state: initialState
}

export default model

// You can use these types when use Class Components.
// type ConsumerActionsType = getConsumerActionsType<typeof Model.actions>
// type ConsumerType = { actions: ConsumerActionsType; state: StateType }
// type ActionType = ConsumerActionsType
// export { ConsumerType, StateType, ActionType }

⇧ back to top

Model Register

react-model keeps the application state and actions in separate private stores. So you need to register them if you want to use them as the public models.

model/index.ts

import { Model } from 'react-model'
import Home from '../model/home'
import Shared from '../model/shared'

const models = { Home, Shared }

export const { getInitialState, useStore, getState, actions, subscribe, unsubscribe } = Model(models)

⇧ back to top

useStore

The functional component in React ^16.8.0 can use Hooks to connect the global store. The actions returned from useStore can invoke dom changes.

The execution of actions returned by useStore will invoke the rerender of current component first.

It's the only difference between the actions returned by useStore and actions now.

import React from 'react'
import { useStore } from '../index'

// CSR
export default () => {
  const [state, actions] = useStore('Home')
  const [sharedState, sharedActions] = useStore('Shared')

  return (



      Home model value: {JSON.stringify(state)}
      Shared model value: {JSON.stringify(sharedState)}
      <button onClick={e => actions.increment(33)}>home increment</button>
      <button onClick={e => sharedActions.increment(20)}>
        shared increment
      </button>
      <button onClick={e => actions.get()}>fake request</button>
      <button onClick={e => actions.openLight()}>fake nested call</button>



  )
}

optional solution on huge dataset (example: TodoList(10000+ Todos)):

  1. use useStore on the subComponents which need it.
  2. use useStore selector. (version >= v4.0.0-rc.0)

advance example with 1000 todo items

⇧ back to top

getState

Key Point: State variable not updating in useEffect callback

To solve it, we provide a way to get the current state of model: getState

Note: the getState method cannot invoke the dom changes automatically by itself.

Hint: The state returned should only be used as readonly

import { useStore, getState } from '../model/index'

const BasicHook = () => {
  const [state, actions] = useStore('Counter')
  useEffect(() => {
    console.log('some mounted actions from BasicHooks')
    return () =>
      console.log(
        `Basic Hooks unmounted, current Counter state: ${JSON.stringify(
          getState('Counter')
        )}`
      )
  }, [])
  return (
    <>


state: {JSON.stringify(state)}


    </>
  )
}

⇧ back to top

actions

You can call other models' actions with actions api

actions can be used in both class components and functional components.

import { actions } from './index'

const model = {
  state: {},
  actions: {
    crossModelCall: () => {
      actions.Shared.changeTheme('dark')
      actions.Counter.increment(9)
    }
  }
}

export default model

⇧ back to top

subscribe

subscribe(storeName, actions, callback) run the callback when the specific actions executed.

import { subscribe, unsubscribe } from './index'

const callback = () => {
  const user = getState('User')
  localStorage.setItem('user_id', user.id)
}

// subscribe action
subscribe('User', 'login', callback)
// subscribe actions
subscribe('User', ['login', 'logout'], callback)
// unsubscribe the observer of some actions
unsubscribe('User', 'login') // only logout will run callback now

⇧ back to top

Advance Concept

immutable Actions

The actions use immer produce API to modify the Store. You can return a producer in action.

Using function as return value can make your code cleaner when you modify the deep nested value.

TypeScript Example

// StateType and ActionsParamType definition
// ...

const model: ModelType<StateType, ActionsParamType> = {
  actions: {
    increment: async (params, { state: s }) => {
      // return (state: typeof s) => { // TypeScript < 3.9
      return state => {
        state.counter += params || 1
      }
    },
    decrease: params => s => {
      s.counter += params || 1
    }
  }
}

export default model

JavaScript Example

const Model = {
  actions: {
    increment: async (params) => {
      return state => {
        state.counter += params || 1
      }
    }
  }
}

⇧ back to top

SSR with Next.js

Store: shared.ts

const initialState = {
  counter: 0
}

const model: ModelType<StateType, ActionsParamType> = {
  actions: {
    increment: (params, { state }) => {
      return {
        counter: state.counter + (params || 1)
      }
    }
  },
  // Provide for SSR
  asyncState: async context => {
    await waitFor(4000)
    return { counter: 500 }
  },
  state: initialState
}

export default model

Global Config: _app.tsx

import { models, getInitialState, Models } from '../model/index'

let persistModel: any

interface ModelsProps {
  initialModels: Models
  persistModel: Models
}

const MyApp = (props: ModelsProps) => {
  if ((process as any).browser) {
    // First come in: initialModels
    // After that: persistModel
    persistModel = props.persistModel || Model(models, props.initialModels)
  }
  const { Component, pageProps, router } = props
  return (
    <Container>
      <Component {...pageProps} />
    </Container>
  )
}

MyApp.getInitialProps = async (context: NextAppContext) => {
  if (!(process as any).browser) {
    const initialModels = context.Component.getInitialProps
      ? await context.Component.getInitialProps(context.ctx)
      await getInitialState(undefined, { isServer: true }) // get all model initialState
      // : await getInitialState({ modelName: 'Home' }, { isServer: true }) // get Home initialState only
      // : await getInitialState({ modelName: ['Home', 'Todo'] }, { isServer: true }) // get multi initialState
      // : await getInitialState({ data }, { isServer: true }) // You can also pass some public data as asyncData params.
    return { initialModels }
  } else {
    return { persistModel }
  }
}

Page: hooks/index.tsx

import { useStore, getState } from '../index'
export default () => {
  const [state, actions] = useStore('Home')
  const [sharedState, sharedActions] = useStore('Shared')

  return (



      Home model value: {JSON.stringify(state)}
      Shared model value: {JSON.stringify(sharedState)}
      <button
        onClick={e => {
          actions.increment(33)
        }}
      >



  )
}

Single Page Config: benchmark.tsx

// ...
Benchmark.getInitialProps = async () => {
  return await getInitialState({ modelName: 'Todo' }, { isServer: true })
}

⇧ back to top

Middleware

We always want to try catch all the actions, add common request params, connect Redux devtools and so on. We Provide the middleware pattern for developer to register their own Middleware to satisfy the specific requirement.

```tsx // Under the hood const tryCatch: Middleware<{}>

Extension points exported contracts — how you extend this code

Global (Interface)
(no doc)
src/index.d.ts
CommonState (Interface)
(no doc)
__test__/index.ts
ModelContext (Interface)
(no doc)
src/index.d.ts
CommonActionParams (Interface)
(no doc)
__test__/index.ts
BaseContext (Interface)
(no doc)
src/index.d.ts
ExpensiveState (Interface)
(no doc)
__test__/index.ts
InnerContext (Interface)
(no doc)
src/index.d.ts
ExpensiveActionParams (Interface)
(no doc)
__test__/index.ts

Core symbols most depended-on inside this repo

useStore
called by 67
src/index.tsx
Model
called by 66
src/index.tsx
getState
called by 27
src/index.tsx
subscribe
called by 22
src/index.tsx
createStore
called by 19
src/index.tsx
useModel
called by 18
src/index.tsx
timeout
called by 11
src/helper.ts
unsubscribe
called by 11
src/index.tsx

Shape

Function 37
Class 14
Interface 12
Method 7

Languages

TypeScript100%

Modules by API surface

src/index.tsx20 symbols
src/middlewares.ts10 symbols
src/index.d.ts8 symbols
src/helper.ts8 symbols
__test__/index.ts5 symbols
__test__/connect.spec.tsx3 symbols
__test__/class/renderProps.spec.tsx3 symbols
__test__/class/mapActions.spec.tsx3 symbols
__test__/class/communicator.spec.tsx3 symbols
__test__/class/class.spec.tsx3 symbols
__test__/lane/lane.spec.ts2 symbols
__test__/lane/react.spec.ts1 symbols

Used by 1 indexed graphs manifest dependencies, hub-wide

For agents

$ claude mcp add react-model \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact