reducer-kit
v1.0.1
Published
100 LOC type-safe react state management with use-reducer for component.
Downloads
5
Readme
reducer-kit
100 LOC type-safe react state management with use-reducer for component.
Usage
import React from "react";
import { render } from "react-dom";
import { Action, createKit, Dispatch, Selector } from "reducer-kit";
const CounterKit = createKit({
initialState: {
count: 0
},
reducers: {
inc(state, action: Action<number>) {
state.count += action.payload;
}
}
});
type CounterKitType = typeof CounterKit;
const inc = (dispatch: Dispatch<CounterKitType>) => {
dispatch({
type: "inc",
payload: 1
});
};
const selectCount: Selector<CounterKitType> = (state) => state.count;
const Counter: React.FC = () => {
const count = CounterKit.useSelector(selectCount);
const dispatch = CounterKit.useDispatch();
return (
<button className="button" onClick={() => inc(dispatch)}>
CLICK {count}
</button>
);
};
const App: React.FC = () => {
return (
<CounterKit.Provider>
<Counter />
</CounterKit.Provider>
);
};
render(<App />, document.body);
Why reducer-kit
- Easy and lightweight, 100 LOC with
use-context-selector
、immer
、anduseReducer
. - Minimal re-render with
useSelector
. - Type safe.
- For component with
Provider
.
Examples
See demo in CodeSandbox.