reduxed-context

0.2.6 • Public • Published

React context API used to replicate a simpler redux state manager

This package aims to help providing a fast replica of redux state manager with a provider and a hook consumer. Wrap you app/component/page with the Provider and its actions/reducers/initialState, and use the hook consumer in any component below.

Only works with react >=16.8

How to use it

Actions

// context/actions.js
const countActions = (id) => ({
    increment: () => ({id: id, type: 'INCREMENT'}),
    decrement: () => ({id: id, type: 'DECREMENT'}),
    reset: () => ({id: id, type: 'RESET'})
})
 
export default (id) => ({
    count: countActions(id),
})

Reducers

// context/reducers.js
const countReducer (state, { type }) => {
    switch (type) {
        case 'INCREMENT':
            state++
            return state
        case 'DECREMENT':
            state--
            return state
        case 'RESET':
            return 0
        default:
            return state
    }
}
 
export default (state, action) => {
    return {
        ...state,
        count: countReducer(state.count, action),
    }
}

Provider

import { Provider } from 'reduxed-context'
 
// Import your actions and reducers
import actions from '../context/actions'
import reducers from '../context/reducers'
 
// Your initial provided state
const providedState = { count: 0, isAuth: false}
 
const YourEnhancedComp = () => <Provider value={ providedState } actions={actions} reducers={reducers}>
    <div> You can use the providedState anywhere below the Provider.</div>
</Provider>

Consumer

import { useCtxActions } from 'reduxed-context'
 
const YourConnectedComp = () => {
    const [{ count, isAuth }, // First object is the providedState 
        { increment, decrement, reset } // Second  object is the reducers
    ] = useCtxActions(['count', 'isAuth'], [['increment', 'decrement', 'reset']]) // First and second array of strings to link the called states and reducers
 
    return <section>
        <button onClick={ increment }> + </button>
        <div>Count: { count }</div>
        <button onClick={ decrement }> - </button>
        <button onClick={ reset }> Reset </button>
        <hr />
    </section>
}
 
export default YourConnectedComp

Package Sidebar

Install

npm i reduxed-context

Weekly Downloads

2

Version

0.2.6

License

ISC

Unpacked Size

9.66 kB

Total Files

6

Last publish

Collaborators

  • delka