SmartCodingTips

🧰 Redux Toolkit (RTK)

Redux Toolkit (RTK) is the official, recommended way to use Redux. It simplifies Redux setup and reduces boilerplate with utilities like createSlice and configureStore.


🚀 1. Installation


npm install @reduxjs/toolkit react-redux

📦 2. Create a Slice

Slices include state, reducers, and actions in one place:


// features/counter/counterSlice.js
import { createSlice } from '@reduxjs/toolkit';

const counterSlice = createSlice({
  name: 'counter',
  initialState: { value: 0 },
  reducers: {
    increment: (state) => { state.value += 1 },
    decrement: (state) => { state.value -= 1 },
  },
});

export const { increment, decrement } = counterSlice.actions;
export default counterSlice.reducer;

🗃 3. Configure the Store


// app/store.js
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from '../features/counter/counterSlice';

export const store = configureStore({
  reducer: {
    counter: counterReducer,
  },
});

🔗 4. Provide the Store

Wrap your app with <Provider> from react-redux:


import ReactDOM from 'react-dom/client';
import { Provider } from 'react-redux';
import { store } from './app/store';
import App from './App';

ReactDOM.createRoot(document.getElementById('root')).render(
  <Provider store={store}>
    <App />
  </Provider>
);

📥 5. Use Redux State in Components


import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement } from './features/counter/counterSlice';

function Counter() {
  const count = useSelector((state) => state.counter.value);
  const dispatch = useDispatch();

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => dispatch(increment())}>+</button>
      <button onClick={() => dispatch(decrement())}>-</button>
    </div>
  );
}

✅ Benefits of Redux Toolkit

  • Less boilerplate than vanilla Redux
  • Built-in Immer.js for immutability
  • Easy integration of async logic via createAsyncThunk
  • DevTools enabled by default