Profile Photo

Using redux for state management

Created on: Jul 28, 2024

Using Redux in your application can offer several benefits, particularly for complex state management scenarios. Here are the key benefits of using Redux:

  1. Centralized State Redux provides a single store for all your application’s state, making it easier to manage and share state across different components.
  2. Redux can be used to manage state in both client and server environments, ensuring consistency across different environments. By combining Redux with libraries like redux-persist, you can easily persist the state between page reloads or even sessions.
  3. Separation of Concerns: Actions, reducers, and the store are kept separate, promoting a clear separation of concerns. This makes the codebase more maintainable.
  4. Compatibility: Redux works well with various libraries and frameworks, including React, Angular, and Vue.
  5. Since data stored in redux persists until page refresh, it is widely used to store long-term data that is required while the user navigates the application, such as, data loaded from an API, data submitted through a form, etc.

We can manage various state using redux in a typical e commerce application like jwt token, product catalog, shopping cart, orders, wishlist.

Let's do a practicle by creating counter state. First create a react app using typescript.

npx create-react-app reduxappsample --template typescript npm install @reduxjs/toolkit react-redux @types/react-redux

Add add below code.

// src/actions.ts export const INCREMENT = "INCREMENT"; export const DECREMENT = "DECREMENT"; interface IncrementAction { type: typeof INCREMENT; } interface DecrementAction { type: typeof DECREMENT; } export type CounterActionTypes = IncrementAction | DecrementAction; export const increment = (): IncrementAction => ({ type: INCREMENT, }); export const decrement = (): DecrementAction => ({ type: DECREMENT, });
// src/reducer.ts import { INCREMENT, DECREMENT, CounterActionTypes } from "./actions"; interface CounterState { count: number; } const initialState: CounterState = { count: 0, }; const counterReducer = ( state = initialState, action: CounterActionTypes ): CounterState => { switch (action.type) { case INCREMENT: return { ...state, count: state.count + 1, }; case DECREMENT: return { ...state, count: state.count - 1, }; default: return state; } }; export default counterReducer;
// src/store.ts import { configureStore } from "@reduxjs/toolkit"; import counterReducer from "./reducer"; const store = configureStore({ reducer: counterReducer, }); export default store; export type RootState = ReturnType<typeof store.getState>; export type AppDispatch = typeof store.dispatch;
// src/App.tsx import React from "react"; import { useSelector, useDispatch } from "react-redux"; import { increment, decrement } from "./actions"; import { RootState, AppDispatch } from "./store"; const App: React.FC = () => { const count = useSelector((state: RootState) => state.count); const dispatch = useDispatch<AppDispatch>(); return ( <div> <h1>Counter: {count}</h1> <button onClick={() => dispatch(increment())}>Increment</button> <button onClick={() => dispatch(decrement())}>Decrement</button> </div> ); }; export default App;
// src/index.tsx import React from "react"; import ReactDOM from "react-dom/client"; import "./index.css"; import App from "./App"; import reportWebVitals from "./reportWebVitals"; import { Provider } from "react-redux"; import store from "./store"; const root = ReactDOM.createRoot( document.getElementById("root") as HTMLElement ); root.render( <React.StrictMode> <Provider store={store}> <App /> </Provider> , </React.StrictMode> ); reportWebVitals();

And run code using below command

npm run start

You can find full code in my github repo