Redux - Redux Toolkit (RTK)
Redux Toolkit (RTK) is the recommended way to write Redux logic. It reduces boilerplate and uses Immer under the hood so you can write "mutating" code that produces immutable updates.
Try it: Counter slice
View source
const { configureStore, createSlice } = RTK;
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 },
reducers: {
inc(state){ state.value += 1; },
dec(state){ state.value -= 1; },
}
});
const store = configureStore({ reducer: { counter: counterSlice.reducer } });
function App(){
const { Provider, useSelector, useDispatch } = ReactRedux;
function Counter(){
const v = useSelector(s => s.counter.value);
const dispatch = useDispatch();
return (
<div>
<div>Value: {v}</div>
<button onClick={() => dispatch(counterSlice.actions.inc())}>+1</button>
<button onClick={() => dispatch(counterSlice.actions.dec())} style={{marginLeft:8}}>-1</button>
</div>
);
}
return <Provider store={store}><Counter /></Provider>;
}
ReactDOM.createRoot(document.getElementById('rtk-root')).render(<App />);
Syntax primer
createSlice({ name, initialState, reducers })
generates action creators + reducer.configureStore({ reducer })
sets up the store with good defaults and devtools.