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'