Global data management hooks like redux.
yarn add react-use-store
yarn add redux redux-store-init
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>
);
}