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

react-connect-state

v4.0.0

Published

Simple, type safe and time travelling state management for React

Downloads

6

Readme

Simple, type safe and time travelling state management for React

Build Status codecov


Usage

import connectToState, { StateContainer } from 'react-connect-state';
import React from 'react';
import ReactDOM from 'react-dom';

interface CounterState {
  count: number;
}

class CounterContainer extends StateContainer<CounterState> {
  state = {
    count: 0
  };

  increment() {
    this.setState({ count: this.state.count + 1 });
  }
}

interface CounterViewProps {
  counter: CounterContainer;
}

const CounterView = ({ counter }: CounterViewProps) => <div>
  <span>{counter.state.count}</span>
  <button onClick={() => counter.increment()}>+</button>
</div>;

const ConnectedCounterView = connectToState(
  CounterView,
  { counter: new CounterContainer() }
);

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

StateContainer<State>

This is a very simple abstract base class that provides a private setState method similar to React which will update the internal state and notify all listeners. Unlike React though, this method is synchronous so there's no danger in reading the current state while updating it.

If your container needs some dependencies in order to work you can pass them through the constructor.

import { StateContainer } from 'react-connect-state';

class MyStateContainer extends StateContainer<{ foo: number }> {
  constructor(private foo: number) {
    super();
    this.state = { foo };
  }
  
  increment() {
    this.setState({ foo: this.foo + 1 });
  }
}

const container = new MyStateContainer(42);
container.increment();
console.log(container.state.foo); // 43

connectToState(View, { [propName]: container })

The method takes a component and a mapping of props to state containers and connects them together so that whenever the containers update their state the view will be re-rendered. The returned HOC will accept the same props as the original component, minus the props that will hold the containers.

You can connect the same container to multiple views in a singleton pattern by just passing the same reference to multiple connect calls.

import connectToState, { StateContainer } from 'react-connect-state';
import React from 'react';

class MyStateContainer extends StateContainer<any> { }
const container = new MyStateContainer();

const View1 = ({ foo }: { foo: StateContainer<any> }) => null;
const View2 = ({ bar }: { foo: StateContainer<any> }) => null;

const ConnectedView1 = connectToState(View1, { foo: container });
const ConnectedView2 = connectToState(View2, { bar: container });

You can also pass multiple containers:

import connectToState, { StateContainer } from 'react-connect-state';
import React from 'react';

class MyStateContainer extends StateContainer<any> { }

interface ViewProps {
  foo: StateContainer<any>,
  bar: StateContainer<any>,
}

const View = ({ foo, bar }: ViewProps) => <div>...</div>;

const ConnectedView = connectToState(View, {
  foo: new MyStateContainer(),
  bar: MyStateContainer()
});

Debugging and time travel

time-travel-todomvc

stateCommitGraph

If you want to see how the state evolves, or who triggered a specific state mutation, the lib exports a state container which holds the graph of all state commits made by all the containers:

import { stateCommitGraph } from 'react-connect-state';

console.log(stateCommitGraph.state.branches[0]);
// [{
//   id: 1,
//   state: { todos: [], typingTodo: 'b' },
//   checkout,
//   instance
// }]

StateCommit

Each setState call in a container will create a new commit in the state commit graph. Each commit has a checkout method which you can use to travel back in time. Checking out a commit will reset every container's state to the state they held at that moment in time.

Branches

After a checkout, any new state commits will create a new branch. This way no commits are overridden and you can easily go back and forth between different paths of your state flow.

CommitGraphDebug

Since the commit graph is a state container you can easily connect it to a view to monitor your app's state in real time. The lib exports a view that is already connected and renders the commit graph in a git tree fashion and allows you to inspect the commits and perform checkouts.

import { CommitGraphDebug } from 'react-connect-state';
import React from 'react';
import ReactDOM from 'react-dom';

ReactDOM.render(<CommitGraphDebug />, document.getElementById('log'));

Motivation

Turn this

import React, { Component } from 'react';

interface ViewState {
  foo: number
}

class View extends Component<{}, ViewState> {
  state = { foo: 1 };
  
  render() {
    return <div>
      Foo is {this.state.foo}
    </div>;
  }
  
  componentDidMount() {
    setInterval(() => this.setState(
      (prevState) => ({ foo: prevState.foo + 1 })
    ), 1000);
  }
}

into this

import connectToState, { StateContainer } from 'react-connect-state';
import React from 'react';

interface FooState {
  foo: number;
}

class FooContainer extends StateContainer<FooState> {
  state = { foo: 1 };
  
  constructor() {
    super();
    
    setInterval(() => {
      this.setState({ foo: this.state.foo + 1 });
    }, 1000);
  }
}

interface ViewProps {
  foo: StateContainer<FooState>
}

const View = (props: ViewProps) => <div>
  Foo is {props.foo.state.foo}
</div>;

const ConnectedView = connectToState(View, { foo: new FooContainer() }); 

Decoupling state from your React views has some advantages. First of all, you can test the state logic and the view logic separately. Secondly, state will become easier to share between components because it will set at a higher level from where it can be passed to multiple components. Lastly, components can become more reusable by accepting a more generic type of state. This becomes evident if you have components that are coupled to APIs - by removing that state and creating a prop interface for it, you can open up the component to receiving similar responses from other APIs as well.

Guiding principles

Type safety

This lib is written in TypeScript and it makes sure that when you connect a view to a state container the view will have a prop interface accepting that type of container.

typescript

Dependency Injection

Pulling away the state from the views and connecting them higher up in the app can lead to loosely coupled components. Views can become more reusable since their state and actions can be expressed through props and callbacks. The state containers are simple classes with a very minimal interface that can be implemented with or without this lib or with other libs.

import connectToState, { StateContainer } from 'react-connect-state';
import React from 'react';

interface DropdownState {
  items: { id: number; name: string; }[];
}

interface DropdownContainer extends StateContainer<DropdownState> {
  delete: (id: number) => void;
}

interface DropdownProps {
  items: DropdownContainer;
}

const Dropdown = ({ items }: DropdownProps) => <select>
  {items.state.items.map(item => <option key={item.id}>
    <span>{item.name}</span>
    <button onClick={items.delete.bind(items, item.id)}>Delete</button>
  </option>)}
</select>;

// We're using the same Dropdown component and binding it to different
// state containers.
const UserDropdown = connectToState(Dropdown, { items: new UsersContainer() });
const ArticlesDropdown = connectToState(Dropdown, { items: new ArticlesContainer() });

Easy testing

Separating state from views enables testing them separately in isolation. Taking the first example from above, the tests might look something like this:

import { describe, it } from 'mocha';
import { spy } from 'sinon';
import { expect } from 'chai';
import { render } from 'some-testing-framework';
import React from 'react';
import { CounterContainer, CounterView } from '../src';

describe('CounterContainer', () => {
  it('should start at zero', () => {
    expect(new CounterContainer().state.count).to.equal(0);
  });
  
  it('should increment', () => {
    const counter = new CounterContainer();
    counter.increment();
    expect(counter.state.count).to.equal(1);
  });
});

describe('CounterView', () => {
  // You can use simple objects as containers.
  const counterMock = {
    state: { count: 23 },
    increment: spy()
  };
  
  it('should display the counter', () => {
    const component = render(<CounterView counter={counterMock} />);
    expect(component.text()).to.include('23');
  });
  
  it('should call to increment', () => {
    const component = render(<CounterView counter={counterMock} />);
    component.click('button');
    expect(counterMock.increment).to.have.been.calledOnce;
  });
});

More examples

Exporting a connected component

You can of course connect a view to a container when exporting it from a module.

import connectToState from 'react-connect-state';
import CounterContainer from './counter-container';

interface CounterViewProps {
  counter: CounterContainer
}

const CounterView = ({ counter }: CounterViewProps) => null;

export default connectToState(CounterView, { counter: new CounterContainer() });

This pattern is perfectly valid, though it couples the view to the state container so it can't be used without it. This increases "out of the box readiness" at the expense of loose coupling.

Connecting a component inline

import connectToState from 'react-connect-state';
import container from './container';
import CounterView from './view';
import React from 'react';

// Connect the view once, outside your render method.
const ConnectedCounterView = connectToState(CounterView, { foo: container });

// And now use it in your exported component.
export default () => <div>
  <ConnectedCounterView />
</div>;

This is the same as exporting a connected component although it happens higher up the call stack - the CounterView component is reusable and can be connected to any container and the component we're exporting binds it to a particular container, effectively binding itself to that container.

Expressing dependencies between containers

You can subscribe to containers via their subscribe method so there's nothing from stopping a container listening to another container: just pass their instances in the constructor and subscribe to them there.

import connectToState, { StateContainer } from 'react-connect-state';
import React from 'react';
import ReactDOM from 'react-dom';

interface ToggleState {
  toggled: number;
}

class Toggle extends StateContainer<ToggleState> {
  state = { toggled: false };
  
  toggle = () => {
    this.setState({ toggled: !this.state.toggled });
  }
}

interface ToggleCountState {
  on: number;
  off: number;
}

const ToggleView = ({ toggle }: { toggle: StateContainer<ToggleState> }) => <div>
  {toggle.state.toggled ? 'I am on' : 'I am off'}
  <button onClick={toggle.toggle}>Toggle me!</button>
</div>;

class ToggleCount extends StateContainer<ToggleCountState> {
  state = { on: 0, off: 0 };
  
  constructor(toggle: StateContainer<ToggleState>) {
    super();
    toggle.subscribe(this.onToggle);
  }
  
  onToggle = (toggleState: ToggleCountState) => {
    if (toggleState.toggled) {
      this.setState({ on: this.state.on + 1 });
    } else {
      this.setState({ off: this.state.off + 1 });
    }
  }
}

const ToggleCountView = ({ toggleCount }: { toggleCount: StateContainer<ToggleCountState> }) => <div>
  <p>Number of times toggled on: {toggleCount.state.on}</p>
  <p>Number of times toggled off: {toggleCount.state.off}</p>
</div>;

const toggle = new Toggle();
const toggleCount = new ToggleCount(toggle);

const ConnectedToggle = connectToState(ToggleView, { toggle: toggle });
const ConnectedToggleCount = connectToState(ToggleCountView, { toggleCount: toggleCount });

ReactDOM.render(<div>
  <ConnectedToggle />
  <ConnectedToggleCount />
</div>, document.getElementById('root'));