DEV Community

Discussion on: Stress Testing React Easy State

Collapse
 
solkimicreb profile image
Miklos Bertalan

Thanks!

I think they are pretty different, context API is used for (buffed up) DI and most state management libs use it as a part of their functionality - usually combined with HOCs. I don't think raw context should be used for state management, but it is a nice building block in some cases.

Easy State does not have built-in DI, because I don't think it's necessary. "Global state is global" and I don't see the point of injecting global, singleton objects in most use cases. This is why I advise everyone to use simple ES6 exports and imports instead. I think context is best used for spread-out local state (where you have to share it between a branch of components but don't want to make it global).

If you need, you can combine Easy State with Context to add some DI to the mix though. As an example, this could be a naive implementation of react-redux for easy state:

import React from 'react'
import { view } from 'react-easy-state'

const { Provider, Consumer } = React.createContext()

function connect(mapStateToProps) {
  return Comp =>
    view(props => (
      <Consumer>
        {state => <Comp {...mapStateToProps(state)} {...props} />}
      </Consumer>
    ))
}

export { Provider, connect }

Summary: I don't think context is enough for state management in its own, but it can be a nice building block. With a little effort, you can make a new state management lib on top of it. Some state management libs do this and use context behind the scenes, easy state is not one of them though.