Redux toolkit boilerplate code for ReactJS / NextJS

Share

redux-toolkit-boilerplate-react

Initializing Redux on our ReactJS or NextJS project would be tricky and this article would be your quick and promising boilerplate. Follow the below steps, to get it configured into your project with ease.

Creating slice

FILE: ./src/store/cart.ts

import { createSlice, createSelector } from "@reduxjs/toolkit";

const initialState = {
  count: 0,
  isProductInsideCart: false,
};

const slice = createSlice({
  name: "cartState",
  initialState: initialState,
  reducers: {
    updateProductInsideCart: (cartState, action) => {
      cartState.isProductInsideCart = action.payload;
    },
    updateItemCount: (cartState, action) => {
      cartState.count += action.payload;
    },
  },
});

// createSelector helps to get updated state values from component after dispatching
type RootState = ReturnType<typeof store.getState>;
export const getCartState = createSelector(
  (state: RootState) => state,
  (cartState) => cartState
);

// export
// actions
export const { updateProductInsideCart, updateItemCount } = slice.actions;
// reducer
export default slice.reducer;

Creating store

FILE: ./src/store/configureStore.ts

import { configureStore } from "@reduxjs/toolkit";
import reducer from "xx";

configureStore({
  reducer: reducer,
});

export default store;

Wrapping ROOT Component with Redux Provider

FILE: ./src/index.tsx

import { Provider } from "react-redux";

// wrap the main App with Redux Provider.
<Provider store={store}>
  <App />
</Provider>;

Component level

FILE: ./src/App.tsx

import { useDispatch, useSelector } from "react-redux";

function App() {
  // generic usage without de-structuring.
  // const state = store.getState();
  // return <div>{state.count}</div>;

  // const {count, isProductInsideCart} = store.getState(); // cannot get updated state values after dispatching. So use selector

  // useSelector to get state values.
  const { count, isProductInsideCart } = useSelector(getCartState);
  // useDispatch to dispatch / update state values in store.
  const dispatch = useDispatch();

  return (
    <>
      <div onClick={() => dispatch(updateItemCount(1))}>
        Cart count: {count}
      </div>
      <button
        isDiabled={isProductInsideCart}
        onClick={() => dispatch(updateProductInsideCart(true))}
      >
        Add to Cart
      </button>
      <button onClick={() => dispatch(updateItemCount(1))}>+</button>
      <button onClick={() => dispatch(updateItemCount(-1))}>-</button>
    </>
  );
}

Share

Thanks and I hope this blog helped you in some way!

Let's stay in touch. :)