English | 中文文档
@nebula-note/redux-hooks is a lightweight solution for state management fully driven by hooks, built on top of Redux, React-Redux, and @reduxjs/toolkit. No actions, no reducers, just hooks.
npm i @nebula-note/redux-hooks
or
yarn add @nebula-note/redux-hooks
The parameters accepted by configureStore are the same as those in @reduxjs/toolkit configureStore. If your project is already using @reduxjs/toolkit, it can be easily switched over.
import { configureStore } from '@nebula-note/redux-hooks';
const store = configureStore();
The usage of useRedux is similar to React’s useState, but it includes an additional parameter for the state name. In the code below, REDUX_KEY corresponds to the state name in the Redux store, equivalent to the name parameter in @reduxjs/toolkit’s createSlice. By using the same REDUX_KEY, you can easily share state data across different pages or components.
import { useRedux } from '@nebula-note/redux-hooks';
const REDUX_KEY = 'exampleReduxName';
type ExampleState = {
count:number
}
export const useExampleRedux = () => {
const { state, setState } = useRedux<ExampleState>(REDUX_KEY, {count:0});
const handleAdd = () => {
setState(state.count + 1);
}
const handleReduce = ()=>{
setState(state.count - 1);
}
return(
<div style={{display:'flex'}}>
<button onclick={handleAdd}>+</button>
<div>{state.count}</div>
<button onclick={handleReduce}>-</button>
</div>
)
}
Here are the methods and properties provided by useRedux:
State data
Return the latest state value in Redux
Set the state value in Redux
Set the state value in Redux synchronously, which is equivalent to setState.The difference is that after using setStateSync, you can use getStateSync to get the latest state.
Update the state value in Redux, and the state value will be merged with the previous state value.The parameter is partial state content. It is particularly important to note that for Array properties, updateState will not merge the Array properties but will directly overwrite the corresponding properties in Redux with the provided data.
Like updateState, after the call is completed, you can use getStateSync to retrieve the latest state data.
This method is used to listen for changes in the submission state of an action. It returns a promise, which is resolved after the action is executed, and it returns a function to cancel the listener.
const takeHandle = take('setState');
takeHandle.then((offTake) => {
console.log('State updated');
offTake();
})
updateState({dataList: resp.data, fetchStatus: 'Success'});
Similar to the take function, but it only executes once. After calling, it returns a promise object, and when resolved, the returned content is empty.