A simple performant approach to state management in React.
- Uses reducers and dispatch π€
- Access state from anywhere with hooks π
- You can still use statically π²
- Optimized for use with Typescript π
- Full control of render performance π₯
- 2kb minified πͺ
I've made a few Codesandboxes to play around with react-slice
npm i react-slice
Create a file and export your hook w/ reducer (fx counterSlice.js)
// counterSlice.js
import { createSlice } from 'react-slice'; // πππ
export default createSlice({
reducer: /*πππ*/ (state, action) => {
switch (action.type) {
case 'increment':
return state + 1;
default:
return state;
}
},
initialState: /*πππ*/ 0,
debugName: 'Counter', // Optional.
});
Then import that file somewhere else (fx App.jsx) π΄ββ οΈ
// App.jsx
import React from 'react';
import counterSlice from './counterSlice'; // πππ
export default function App(test) {
const counterState = counterSlice.use(); // πππ
const onClick = () => {
counterSlice.dispatch({ type: 'increment' }); // πππ
};
return (
<div className="App">
<h1>{counter /*πππ*/}</h1>
<button onClick={onClick}>Increment</button>
</div>
);
}
And boom! π₯ That's all you need to get up and running!
- API for createSlice()
- Avoid unnecessary re-renders
- Use statically from utils etc.
- Use Typescript and get strongly typed state and actions π
- Use with Server-side rendering (coming soon, would love ideas/usecases)
- Debugging is disabled when
process.env
is 'production' or 'test'