srinivasdamam / storehook

silly state management library built with hooks

Home Page:https://codesandbox.io/s/0nnp8o44v

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool



silly state management library built with hooks

 

⚠️ Hooks are still in alpha, this is just an example library. Don't use this on production.

 

install

npm install storehook

storehook has a peer dependency of react@16.7

 

usage

import React from 'react'
import { Provider, useStore } from 'storehook'
import reducer from './reducer'

/*
  Call useStore inside a functional component
  to get a tuple of store and dispatch function
*/

const Counter = props => {
  const [store, dispatch] = useStore()

  const increase = () => dispatch({ type: 'INCREASE' })
  const decrease = () => dispatch({ type: 'DECREASE' })

  return (
    <p>
      <span onClick={increase}>+</span>
      <span id="badge">{store.count}</span>
      <span onClick={decrease}>-</span>
    </p>
  )
}

/* Wrap your top level App component in a Provider with the reducer */
export default () => (
  <Provider reducer={reducer}>
    <App />
  </Provider>
)

/*
  This is what the reducer looks like
  Don't forget to provide initial state in the reducer
*/

const initialState = { count: 0 }
const reducer = (state = initialState, action) => {
  switch (action.type) {
    case 'INCREASE':
      return {
        ...state,
        count: state.count + 1
      }
    case 'DECREASE':
      return {
        ...state,
        count: state.count - 1
      }
    default:
      return state
  }
}

 

Usage with class components

storehook exports a connect higher order component that can be used with class components

import React from 'react'
import { Provider, connect } from 'storehook'
import reducer from './reducer'

class ClassCounter extends React.Component {
  increase = () => this.props.dispatch({ type: 'INCREASE' })
  decrease = () => this.props.dispatch({ type: 'DECREASE' })

  render() {
    return (
      <p>
        <span onClick={this.increase}>+</span>
        <span id="badge">{this.props.count}</span>
        <span onClick={this.decrease}>-</span>
      </p>
    )
  }
}

/*
  Use connect from storehook to get access to the store variables and
  dispatch function in props
*/
const ConnectedCounter = connect(ClassCounter)

/* Wrap your top level App component in a Provider with the reducer */
export default () => (
  <Provider reducer={reducer}>
    <App />
  </Provider>
)

how does it work?

Check out the source code, it's ~70 lines with comments

 

like it?

⭐ this repo

 

license

MIT © siddharthkp

About

silly state management library built with hooks

https://codesandbox.io/s/0nnp8o44v


Languages

Language:JavaScript 82.3%Language:HTML 14.0%Language:CSS 3.7%