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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@jbknowledge/react-models

v0.2.1

Published

Global state management library with hooks

Downloads

7

Readme

React Models

Global state management in the world of hooks.

Wrap your app

import { ModelProvider } from '@jbknowledge/react-models';

ReactDOM.render(
  <ModelProvider>
    <App />
  </ModelProvider>,
  document.getElementById('root')
);

Define a Model

import { buildModel } from '@jbknowledge/react-models';

const model = {
  name: 'users',
  state: {
    // initial state
    12: {
      id: 12,
      firstName: 'John',
      lastName: 'Doe'
    },
    34: {
      id: 34,
      firstName: 'Jane',
      lastName: 'Doe'
    }
  },
  reducers: {
    setUser: (state, param) => state // immutable reducers
  },
  effects: (dispatch) => ({
    // run async side effects
    addUserAsync: async (user) => {
      // access reducers for all models
      dispatch.users.setUser({
        id: uuid(),
        ...user
      });
    }
  })
};

export const useUsers = buildModel(model);

Read from Global State

import useUsers from './modelDefinition';

const ListView = () => {
  const allUsers = useUsers();
  ...
}

Pass in Model effects as props

import { withModelEffects } from '@jbknowledge/react-models';

const Component = ({ addUserAsync }) => {...};

const mapEffects = ({
  users: { addUserAsync }
}) => ({
  addUserAsync
});

export default withModelEffects(mapEffects)(Component);

Installation

npm install @jbknowledge/react-models

API

This library exports the following:

  • buildModel
  • ModelProvider
  • withModelEffects

buildModel(modelDefinition)

buildModel is a react hook factory.

const useItems = buildModel(itemDefinition);

const Component = () => {
  const allItems = useItems();
};

buildModel expects a single argument: modelDefinition which must match the following schema.

{
  "name": "[string.unique.required]",
  "state": "[any.optional]",
  "reducers": {
    "*": "[function.optional]"
  },
  "effects": "[function.optional]",
  "mapStateToList": "[function.optional]"
}

name: A unique identifier for the model. This is used when accessing reducers from effects and when accessing effects from withModelEffects. This param is the only required param and should almost always be unique.

i.e.

const modelDefinition = {
  ...,
  name: 'unique',
  reducers: {
    apply: (state, param) => state,
  },
  effects: dispatch => ({
    applyAsync: async (param) => {
      dispatch.unique.apply(param);
      /*
        Our effect is able to access the reducer "apply" via
        dispatch[name][reducerName].
      */
    }
  })
}

const Component = ({ applyAsync }) => (...);

const mapEffects = (models) => ({
  applyAsync: models.unique.applyAsync,
});
/*
  Our mapping function which is passed into "withModelEffects"
  has access to the effect "applyAsync" via models[name][effectName].
*/

export default withModelEffects(mapEffects)(Component);

state: Optionally declare your model's initial state. If excluded, your initial state will default to an empty object.

reducers: Optionally declare one or more reducers for your model state. Each key should be a function which takes the current state and a param and returns the new state:

const reducer = (oldState, param) => {
  const newState = ...;
  return newState;
}

These reducers are accessible to all model effects via dispatch[modelName][reducerName]. For example:

const model = {
  ...,
  name: 'items',
  reducers: {
    apply: (state, param) => state
  }
};

will be accessible to model effects as dispatch.items.apply.

Note: model reducers can have at most two args, the current state, and a param. If you need to pass in multiple values, we recommend using an object as your param, i.e.

const model = {
  ...,
  name: 'items',
  effects: dispatch => ({
    applyAsync: async () => {
      dispatch.items.apply({
        arg1: 'value',
        arg2: true,
      });
    }
  })
}

In this case, your reducer definition will receive a param which is equal to: { arg1: 'value', arg2: true }.

effects: Optionally declare one or more model side effects via an object factory. The effects key must be a function and will recieve a single argument, dispatch, which contains all reducers for all models, not just the model being defined.

// items model definition
const items = {
  ...,
  name: 'items',
  reducers: {
    setItem: ...
  }
};

// things model definition
const things = {
  ...,
  name: 'things',
  reducers: {
    setThing: ...
  },
  effects: dispatch => ({
    applyAsync: async () => {
      dispatch.items.setItem();
      dispatch.things.setThing();
      /*
        All effects can access all model's reducers
      */
    }
  })
}

mapStateToList: Optionally declare a mapping function to convert your state into a list of items. By default, it is assumed that your state is structured like the following:

{
  [id]: [entity],
  [id]: [entity],
  ...
}

i.e.

{
  12: { "id": 12, "firstName": "john", "lastName": "doe" },
  34: { "id": 34, "firstName": "jane", "lastName": "doe" }
}

If your state matches this structure, then you do not need to specify mapStateToList. In all other cases, you will need to declare mapStateToList as a function which takes your state and returns an array of entities.

i.e.

const model = {
  ...,
  state: {
    nextId: 0,
    items: [
      {...},
      {...},
      ...
    ]
  },
  mapStateToList: state => state.items,
}

buildModel generated hooks

buildModel's return value is a react hook which can be used to pull entities of that type out of global state.

const useItems = buildModel(itemDefinition);

const Component = () => {
  const allItems = useItems();
};

More specifically, it returns a function useModel(param).

param: Optionally pass in to filter/transform/sort/etc your items. param itself can be either an object or a function.

NOTE: React models does not support anonymous objects or functions as params for the generated useModel(param) hooks. Guaranteeing referential equality between renders can be achieved with React's useCallback and useMemo hooks and are the responsibility of the user.

typeof param === 'object'

If you call the built model hook with an object parameter, then you will recieve all entities which exactly match each specified key. For example:

const model = {
  ...,
  state: {
    0: { firstName: 'John', lastName: 'Doe' },
    1: { firstName: 'George', lastName: 'Washington' },
    2: { firstName: 'Jane', lastName: 'Doe' },
  }
}

const useModel = buildModel(model);

const Component = () => {
  const filteredUsers = useModel({ lastName: 'Doe' });
  /*
    useModel will return all entities which have the key "firstName" which
    exactly matches "Doe". In this case, it would return:
    [
      { firstName: 'John', lastName: 'Doe' },
      { firstName: 'Jane', lastName: 'Doe' }
    ]
  */
}

typeof param === 'function'

Alternative to the more restrictive object param which filters by exact matches, you can pass in a callback function instead. This function will be called with all entities currently in your global state and will pass the return value as the output of the useModel hook. In this callback, you can filter via more complex rules, sort, transform/map your entities, or anything else you desire.

const Component = () => {
  const sorted = useModel(items => items.sort(...));
  const numJohns = useModel(items => items.filter(...).reduce(..., 0));
  // etc
}

ModelProvider

ModelProvider takes no props and implicitly manages all of your global state for each model on your behalf. It is recommended to wrap your entire App like the following:

import { ModelProvider } from '@jbnowledge/react-models';

ReactDOM.render(
  <ModelProvider>
    <App />
  </ModelProvider>,
  document.getElementById('root')
);

withModelEffects(mapEffects)(Component)

withModelEffects is an HoC which allows you to inject any model's effects into your component as props.

mapEffects: A Function which is provided all effects nested by model, i.e. models.items.applyAsync, and expects an object to be returned.

const mapEffects = (models) => ({
  apply: models.items.applyAsync
});

The object that is returned will be applied to the Component your provide as an argument as props.

Component: The react component which needs model effects to be injected in.


const Component = ({ someEffect }) => (...);

const mapEffects = ({
  items: { someEffect },
}) => ({ someEffect });

export default withModelEffects(mapEffects)(Component);
/*
  This results in the component <Component someEffect={models.items.someEffect} />
*/

Contributors

react-models was built and is maintained by JBKLabs, JBKnowledge Inc's research and development team.

Licensing

This package is licensed under Apache License, Version 2.0. See LICENSE for the full license text.