https://github.com/sasa-djuric/react-use-slice
A react hook to use reducers with an API like createSlice from Redux toolkit, in a typesafe way, with performance in mind.
https://github.com/sasa-djuric/react-use-slice
react react-hooks reducer redux state-management typescript use-reducer
Last synced: about 2 months ago
JSON representation
A react hook to use reducers with an API like createSlice from Redux toolkit, in a typesafe way, with performance in mind.
- Host: GitHub
- URL: https://github.com/sasa-djuric/react-use-slice
- Owner: sasa-djuric
- License: mit
- Created: 2021-05-30T16:31:28.000Z (almost 4 years ago)
- Default Branch: master
- Last Pushed: 2021-12-09T15:07:44.000Z (over 3 years ago)
- Last Synced: 2025-02-12T05:43:21.019Z (3 months ago)
- Topics: react, react-hooks, reducer, redux, state-management, typescript, use-reducer
- Language: TypeScript
- Homepage:
- Size: 25.4 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# react-use-slice
A react hook to use reducers with an API like createSlice from Redux toolkit, in a typesafe way, with performance in mind.
## Install
```sh
npm install react-use-slice
```## Example
#### JavaScript
```js
import { createContext } from 'react';
import useSlice from 'react-use-slice';const initialState = {
score: 0
};const scoreSlice = {
name: 'score', // "name" is optional. It is used in dev tools
initialState,
reducers: {
increment(state, payload) {
const score = state.score + 1;
return { ...state, score };
},
decrement(state, payload) {
const score = state.score - 1;
return { ...state, score };
}
}
};export const ScoreContext = createContext(null);
export const ScoreProvider = ({ children }) => {
// Actions will be automaticaly dispatched
const [state, actions] = useSlice(scoreSlice);return (
{children}
);
};
```#### TypeScript
```ts
import { createContext } from 'react';
import useSlice, { createSlice, CombineStateAndActions } from 'react-use-slice';const initialState = {
score: 0
};const scoreSlice = createSlice({
name: 'score', // "name" is optional. It is used in dev tools
initialState,
reducers: {
increment(state, payload: number) {
const score = state.score + 1;
return { ...state, score };
},
decrement(state, payload: number) {
const score = state.score - 1;
return { ...state, score };
}
}
});export const ScoreContext =
createContext | null>(null);export const ScoreProvider = ({ children }) => {
// Actions will be automaticaly dispatched
const [state, actions] = useSlice(scoreSlice);return (
{children}
);
};
```