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

codux

v0.0.9

Published

Predictable state container for self-contained React components

Downloads

17

Readme

codux

Predictable state container for self-contained React components

Features

  • 2kb! (minified)
  • No dependencies (other than React)
  • Avoid repetitive props and callbacks throughout deeply nested components
  • Improved performance via React.PureComponent
  • Redux inspired API

Demo

Table of Contents

Installation

$ yarn add codux

Example

import React from 'react'
import { Provider, Connect } from 'codux'


const Count = ({ count }) => ({
  <span>{count}</span>
}
// Use Connect to subscribe to values from the Provider state
const ConnectedCount = Connect(state => ({
  count: state.count
}))(Count)

// Every Connected component can use the 'dispatch' prop
// to update the Provider's store
const Increment = ({ dispatch }) => ({
  <button
    // 'dispatch' takes a function that receives the
    // current provider state and returns a new one.
    onClick={() => dispatch(state => ({
      ...state,
      count: state.count + 1 // Immutable is best for performance :)
    }))}
  >
    Increment Count
  </button>
}
const ConnectedIncrement = Connect()(Increment)

const Demo = () => (
  <div>
    <ConnectedCount />
    <ConnectedIncrement />
  </div>
)

// A Provider is a new instance of state for all nodes inside it
export default Provider(Demo)

Provider

The Provider higher-order component creates a new state that wraps the component you pass it. You can nest Providers inside each other, and when doing so, Connected components inside them will connect to the nearest parent Provider. You can also give Providers an initial state in an optional config object.

Creating a Provider
const ProviderWrappedComponent = Provider(MyComponent)
Initial State
const ProviderWrappedComponent = Provider(MyComponent, {
  // the initial state of the provider
  initial: {
    foo: 1,
    bar: 'hello'
  }
})
Passing props as state

Any props you pass to a Provider will be merged with the state and overwrite any same-key values.

<ProviderWrappedComponent
  foo={1}
  bar='hello'
/>
Programatic Control

If you ever need to programmatically dispatch to a provider, you can use a ref!

<ProviderWrappedComponent
  ref={provider => {
    provider.dispatch
  }}
/>

Connect

The Connect higher-order component subscribes a component to any part of the nearest parent Provider, and also provides the component the dispatch prop for updating the state.

Subscribing to state

To subscribe to a part of the provider state, we use a function that takes the state (and component props) and returns a new object with parts of the state you're interested in. Any time the values of that object change, your component will be updated! (There is no need to return props that already exist on your component. The 'props' argument is simply there as an aid in calculating the state you need to subscribe to)

class MyComponent extends Component {
  render () {
    return (
      <div>
        // This 'foo' prop comes from our Connect function below
        <div>{ this.props.foo }</div>
      </div>
    )
  }
}
const MyConnectedComponent = Connect(state => {
  return {
    foo: state.foo // Any time 'foo' changes, our component will update!
  }
})
Using the 'dispatch' prop

Every connected component receives the 'dispatch' prop. You can use this 'dispatch' function to update the provider state. Just dispatch a function that takes the current state and returns a new version of the state. It's very important to make changes using immutability and also include any unchanged parts of the state. What you return will replace the entire state!

class MyComponent extends Component {
  render () {
    return (
      <div>
        <button
          onClick={this.props.dispatch(state => {
            return {
              ...state, // include unchanged parts of the state
              foo: Math.ceil(Math.random() * 10) // update our new random 'foo' value
            }
          })}
        >
          Randomize Foo
        </button>
      </div>
    )
  }
}
const MyConnectedComponent = Connect()(MyComponent)
Memoization and Selectors

If you need to subscribe to computed or derived data, you can use a memoized selector. This functions exactly as it does in Redux. For more information, and examples on usage, please refer to Redux - Computing Derived Data

class MyComponent extends Component {
  render () {
    return (
      <div>
        <div>{ this.props.computedValue }</div>
      </div>
    )
  }
}
const MyConnectedComponent = Connect((state, props) => {
  return {
    computedValue: selectMyComputedValue(state, props)
  }
})
Dispatch Meta

Any time you dispatch, you have the option to send through a meta object. This is useful for middlewares, hooks, and other optimization options throughout Codux.

class MyComponent extends Component {
  render () {
    return (
      <div>
        <button
          onClick={this.props.dispatch(state => ({
            ...state,
            foo: Math.Ceil(Math.random() * 10)
          }, {
            // you can use any object as meta
            mySpecialValue: 'superSpecial'
          })}
        >
          Randomize Foo
        </button>
      </div>
    )
  }
}
const MyConnectedComponent = Connect()(MyComponent)
Connect Config

Connect can be customized for performance and various other enhancments:

  • filter(oldState, newState, meta): Only run connect if this function returns true. Useful for avoiding high-velocity dispatches or general performance tuning.
  • statics{}: An object of static properties to add to the connected component's class.
class MyComponent extends Component { ... }
const MyConnectedComponent = Connect(
  state => {...},
  {
    // Using the following 'filter' function, this Connect will not run if 'meta.mySpecialValue === 'superSpecial'
    filter: (oldState, newState, meta) => {
      return meta.mySpecialValue ? meta.mySpecialValue !== 'superSpecial' : true
    },

    // The Connected component class will also gain these statics
    statics: {
      defaultProps: {
        someProp: 'hello!'
      }
    }
  }
)(MyComponent)

Contributing

To suggest a feature, create an issue if it does not already exist. If you would like to help develop a suggested feature follow these steps:

  • Fork this repo
  • $ yarn
  • $ yarn run storybook
  • Implement your changes to files in the src/ directory
  • View changes as you code via our React Storybook localhost:8000
  • Make changes to stories in /stories, or create a new one if needed
  • Submit PR for review

Scripts

  • $ yarn run storybook Runs the storybook server
  • $ yarn run test Runs the test suite
  • $ yarn run prepublish Builds for NPM distribution
  • $ yarn run docs Builds the website/docs from the storybook for github pages