Coder Social home page Coder Social logo

statty's Introduction

statty

A tiny and unobtrusive state management library for React and Preact apps

Travis Code Coverage David npm npm JavaScript Style Guide MIT License

The current size of statty/dist/statty.umd.min.js is:

gzip size

The problem

Most of the time, I see colleagues starting React projects setting up Redux + a bunch of middlewares and store enhancers by default, regardless of the project nature.

Despite Redux being awesome, it's not always needed and it may slow down the process of onboarding new developers, especially if they are new to the React ecosystem (I have often seen colleagues being stuck for hours trying to understand what was the proper way to submit a simple form).

React already comes with a built-in state management mechanism, setState(). Local component state is just fine in most of the cases.

In real world apps we often have app state, and sometimes it becomes annoying to pass it down the entire component tree, along with callbacks to update it, via props.

This solution

statty is meant to manage app-wide state and can be thought of as a simplified version of Redux.

It safely leverages context to expose application state to children, along with a function to update it when needed.

The update function acts like Redux dispatch, but instead of an action, it takes an updater function as a parameter that returns the new state.

This way it's easy to write testable updaters and to organize them as you prefer, without having to write boilerplate code.

Table of Contents

Installation

This project uses node and npm. Check them out if you don't have them locally installed.

$ npm i statty

Then with a module bundler like rollup or webpack, use as you would anything else:

// using ES6 modules
import statty from 'statty'

// using CommonJS modules
var statty = require('statty')

The UMD build is also available on unpkg:

<script src="https://unpkg.com/statty/dist/statty.umd.js"></script>

You can find the library on window.statty.

Usage

// https://codesandbox.io/s/rzpxx0w34
import React from 'react'
import { render } from 'react-dom'
import { Provider, State } from 'statty'
import inspect from 'statty/inspect'

// selector is a function that returns a slice of the state
// if not specified it defaults to f => f
const selector = state => ({ count: state.count })

// updaters

// updaters MUST be pure and return a complete new state,
// like Redux reducers
const onDecrement = state => 
  Object.assign({}, state, { count: state.count - 1 })

const onIncrement = state =>
  Object.assign({}, state, { count: state.count + 1 })

// Counter uses a <State> component to access the state
// and the update function used to execute state mutations
const Counter = () => (
  <State
    select={selector}
    render={({ count }, update) => (
      <div>
        <span>Clicked: {count} times </span>
        <button onClick={() => update(onIncrement)}>+</button>{' '}
        <button onClick={() => update(onDecrement)}>-</button>{' '}
      </div>
    )}
  />
)

// initial state
const initialState = {
  count: 0
}

// The <Provider> component is supposed to be placed at the top
// of your application. It accepts the initial state and an inspect function
// useful to log state mutatations during development
// (check your dev tools to see it in action)
const App = () => (
  <Provider state={initialState} inspect={inspect}>
    <Counter />
  </Provider>
)

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

The <Provider> component is used to share the state via context. The <State> component takes 2 props:

  • select is a function that takes the entire state, and returns only the part of it that the children will need
  • render is a render prop that takes the selected state and the update function as parameters, giving the user full control on what to render based on props and state.

State updates happen via special updater functions that take the old state as a parameter and return the new state, triggering a rerender.

An updater function may return the slice of the state that changed or an entire new state. In the first case the new slice will be shallowly merged with old state.

API

<Provider>

Makes state available to children <State>

props

state

object | required

The initial state

inspect

function(oldState: object, newState: object, updaterFn: function)

Use the inspect prop during development to track state changes.

statty comes with a default logger inspired by redux-logger.

<Provider
  state={{count: 0}}
  inspect={require('statty/inspect')}
/>

<State>

Connects children to state changes, and provides them with the update function

props

select

function(state: object) | defaults to s => s | returns object

Selects the slice of the state needed by the children components.

render

function(state: object, update: function) | required

A render prop that takes the state returned by the selector and an update function.

Examples

Examples exist on codesandbox.io:

If you would like to add an example, follow these steps:

  1. Fork this codesandbox
  2. Make sure your version (under dependencies) is the latest available version
  3. Update the title and description
  4. Update the code for your example (add some form of documentation to explain what it is)
  5. Add the tag: statty:example

Inspiration

Tests

$ npm run test

LICENSE

MIT License ยฉ Alessandro Arnodo

statty's People

Contributors

exon avatar jwebcoder avatar nickdima avatar rupshabagchi avatar titanve avatar vesparny avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

statty's Issues

performance issue with huge subtree

the problem

I've tried to implement the redux tree-view example with statty and I've noticed a big performance impact in such a scenario.

Problem being that subscribing 1000+ nodes to state changes forces a rerender of the entire tree every time.

Personally I've never hit this use-case in real apps I've built but I think investigating possible solutions is probably worth.

I've created a codesanbox to showcase the problem.

https://codesandbox.io/s/k96o8wpy5o

As you can see all the tree rerenders on every state change

possible solution

ATM we call setState on every state change. I was wondering if there is a way to avoid this behaviour.

As we use a select function to get only the state we need for rendering the single node and its children, we could probably use the same select function to get the old state, do a shallow comparison with the new one, and setState() only if the comparison returns false.

This way I think only nodes interested by the state change will render, instead of the whole tree.

@kentcdodds and @busypeoples any thoughts?

Synchronous actions / callback pattern?

What would be a reasonable way to implement a callback after an update function, such as closing a popover after an update action is triggered?

onClick={() => {
  update(myUpdater(value))
  closeThatSucka()
}

This works well enough for me because my second function doesn't relate to updating the statty store, but I could see needing it in the future.

onClick={() => {
  update(myUpdater(value),  closeThatSucka())
}

Feels more contemporary.

Nested state

I've been playing around with this library and I think it's ready to be promoted a little bit ๐Ÿ˜„ .

There is codesanbox here including the classic and simple counter example plus other more complex async interactions.

One of the things I really enjoyed using redux was reducers composition.
Since statty does not have a concept of actions nor reducers, dealing with nested state might become a bit cumbersome.
The reason is that updater functions get as unique parameter the whole state tree, that must be modified and returned to be then merged with the old state.

In my codesandbox I tried to use Ramda to ease state mutations, but I am not sure neither if I did it right (I started playing with Ramda like couple hours ago ) nor if there is potentially a better way for doing this at library level.

I know @busypeoples is the king of Ramda ๐Ÿ˜„ so he might be able to advice here.

I am basically looking for a good pattern to apply for state transitions more complex than a simple counter that increments/decrements.

Here another codesandbox containing only the Wikipedia example (just for clarity) you can play with.

https://codesandbox.io/s/mQJl3qB2G

import React from 'react'
import Rx from 'rxjs'
import R from 'ramda'
import jsonp from 'jsonp'
import { State } from 'statty'

// updaters
const loadPosts = state => ({ wiki: R.evolve({ loading: R.T })(state.wiki) })
const updateTopic = topic => state => ({
  wiki: R.evolve({ topic: R.always(topic) })(state.wiki)
})
const postsLoaded = data => state => ({
  wiki: R.evolve({
    posts: R.always(R.ifElse(Array.isArray, R.identity, R.always([]))(data)),
    loading: R.F
  })(state.wiki)
})

//selector
const getWikiSliceFromState = R.view(R.lensProp('wiki'))

class WikipediaContainer extends React.Component {
  render() {
    return (
      <State
        select={getWikiSliceFromState}
        children={(state, update) => <Wikipedia {...state} update={update} />}
      />
    )
  }
}

const request = topic => Rx.Observable.bindNodeCallback(jsonp)

const wikipediaService = update => {
  const eventsSubject = new Rx.Subject()
  return {
    init(topic) {
      eventsSubject
        .startWith(topic)
        .debounceTime(300)
        .distinctUntilChanged()
        .do(() => update(loadPosts))
        .switchMap(t =>
          request(t)(
            `https://en.wikipedia.org/w/api.php?action=opensearch&format=json&search=${t}`,
            null
          )
        )
        .subscribe(data => update(postsLoaded(data[1])))
    },
    updateTopic(topic) {
      eventsSubject.next(topic)
    }
  }
}

class Wikipedia extends React.Component {
  service = wikipediaService(this.props.update)

  componentDidMount() {
    this.service.init(this.props.topic)
  }

  componentWillReceiveProps(nextProps) {
    this.service.updateTopic(nextProps.topic)
  }

  render() {
    const { loading, topic, posts, update } = this.props
    return (
      <div>
        <input
          type="text"
          onChange={e => update(updateTopic(e.target.value))}
          value={topic}
        />
        {loading
          ? <div>loading...</div>
          : <div>
              {posts.map((el, i) =>
                <div key={i}>
                  {el}
                </div>
              )}
            </div>}
      </div>
    )
  }
}

export default WikipediaContainer

where the initial state is

import React from 'react'
import { render } from 'react-dom'
import Wikipedia from './Wikipedia'
import { Provider } from 'statty'


const initialState = {
  wiki: {
    topic: 'roger federer',
    posts: [],
    loading: true
  }
}

const App = () =>
  <Provider state={initialState}>
    <div>
      <h4>Wikipedia searchbox using Rx</h4>
      <Wikipedia />
    </div>
  </Provider>

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

thanks a lot to anybody willing to contribute to the discussion ๐Ÿ‘

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.