Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/phryneas/use-local-slice
A react hook to use reducers for local state in a typesafe way, with an API like createSlice from redux-starter-kit and immer integration.
https://github.com/phryneas/use-local-slice
library
Last synced: 3 months ago
JSON representation
A react hook to use reducers for local state in a typesafe way, with an API like createSlice from redux-starter-kit and immer integration.
- Host: GitHub
- URL: https://github.com/phryneas/use-local-slice
- Owner: phryneas
- License: mit
- Created: 2019-04-07T19:41:37.000Z (almost 6 years ago)
- Default Branch: main
- Last Pushed: 2023-01-15T15:28:55.000Z (about 2 years ago)
- Last Synced: 2024-10-03T12:29:00.125Z (4 months ago)
- Topics: library
- Language: TypeScript
- Homepage: https://www.npmjs.com/package/use-local-slice
- Size: 632 KB
- Stars: 41
- Watchers: 4
- Forks: 6
- Open Issues: 4
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
- awesome-list - use-local-slice - starter-kit and immer integration. | phryneas | 22 | (TypeScript)
README
# use-local-slice
An opinionated react hook to use reducers for local state
- in a typesafe way
- with an API like [createSlice](https://redux-starter-kit.js.org/api/createslice) from [redux-starter-kit](https://redux-starter-kit.js.org)
- with [immer](https://github.com/mweststrate/immer) integration## How to use it
```typescript
const [state, dispatchAction] = useLocalSlice({
slice: "my slice", // optional - will be displayed in the debug tools
initialState: { data: "initial text", someOtherValue: 5 },
reducers: {
concat: (state, action: { payload: string }) => {
// reducers are passed an immer draft of the current state, so you can directly modify values in the draft
state.data += action.payload;
},
toUpper: state => ({
// or you return a modified copy yourself
...state,
data: state.data.toUpperCase()
})
// more reducers ...
}
});
```and in some callback:
```typescript
dispatchAction.concat("concatenate me!");
// or
dispatchAction.toUpper();
```use-local-slice provides one dispatchAction method per reducer, and (for typescript users) ensures that these dispatchers are only called with correct payload types.
## Edge case uses & good to know stuff
- reducers can directly reference other local component state & variables without the need for a `dependencies` array. This is normal `useReducer` behaviour. You can read up on this on the overreacted blog: [Why useReducer Is the Cheat Mode of Hooks](https://overreacted.io/a-complete-guide-to-useeffect/#why-usereducer-is-the-cheat-mode-of-hooks)
- you can exchange reducers for others between renders - as long as the keys of the `reducers` property do not change, you will get an identical instance of `dispatchAction`.
- only renaming, adding or removing keys will get you a new `dispatchAction` instance