1.0.3 • Published 5 years ago

react-use-store v1.0.3

Weekly downloads
2
License
MIT
Repository
github
Last release
5 years ago

React-use-store

Global data management hooks like redux.

Install

yarn add react-use-store
yarn add redux redux-store-init

Usage

First, create a store, just like using react-redux.

import React from 'react';
import Store from 'redux-store-init';
import { Provider } from 'react-use-store';
import * as reducers from './reducers';
import App from './app';

const store = Store({ reducers });

ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>
    ,
    document.getElementById('root')
);

To create a Reducer in the reducers.js file, you need to use the createReducer function provided by the react-use-store. Its first argument is the name of the module, and the second argument is the initial state value.

// reducers.js
import { createReducer } from 'react-use-store';

// createReducer(name, initState)
export const index = createReducer('index', {
    count: 1,
});

Then use uer-store in the component to get the global data. You can use commit to submit updates.

import React from 'react';
import useStore from 'react-use-store';

export default function app() {
    const [state, commit, rootState] = useStore('index');

    return (
        <div>
            <div>Count: {state.count}</div>
            <button onClick={e => {
                commit({ count: state.count + 1 })
            }}>update</button>

            <pre style={{ fontFamily: 'consolas' }}>
                {JSON.stringify(rootState, null, 2)}
            </pre>
        </div>
    );
}

npm.io