Skip to content

Instantly share code, notes, and snippets.

@akulsr0
Created March 2, 2022 11:43
Show Gist options
  • Save akulsr0/5eaf1fe7b5ae40fe2eb44922f5cc1360 to your computer and use it in GitHub Desktop.
Save akulsr0/5eaf1fe7b5ae40fe2eb44922f5cc1360 to your computer and use it in GitHub Desktop.

Using Redux in ReactJS

  1. Install redux and react-redux

  2. Create state (src/redux/state.js)

// src/redux/state.js

export const numState = {
  c: 0,
};
export const stringState = {
  s: "This is some text",
};
  1. Create type (src/redux/types.js)
// src/redux/types.js

export const NUM_TYPES = {
  ADD: "ADD",
  SUB: "SUB",
};

export const STRING_TYPES = {
  UPPERCASE: "UPPERCASE",
  LOWERCASE: "LOWERCASE",
};
  1. Create reducer (src/redux/reducer.js)

    1. Import initial state and types required
    function numReducer(state = numState, action) {
      switch (action.type) {
        case NUM_TYPES.ADD:
          return { ...state, c: state.c + action.payload.n };
        case NUM_TYPES.SUB:
          return { ...state, c: state.c - action.payload.n };
        default:
          return state;
      }
    }
    1. You can create multiple reducers.
    2. Combine them using redux.combineReducers
    import { combineReducers } from "redux";
    
    function numReducer(state = numState, action) { ... }
    function stringReducer(state = stringState, action) { ... }
    
    export default combineReducers({ numReducer, stringReducer });
  2. Create store (src/redux/store.js)

// src/redux/store.js
import { createStore } from "redux";
import reducer from "./reducer";

export default createStore(reducer);
  1. Getting Values
import { useSelector } from "react-redux";

const myState = useSelector((s) => s.numReducer);
  1. Dispatching action (Changing global state)
// src/redux/actions.js

import store from "./store";
import { NUM_TYPES } from "./types";

export function numAdd(x) {
  store.dispatch({
    type: NUM_TYPES.ADD,
    payload: { n },
  });
}
@chandninigam
Copy link

We need to add Provider in index.js
Step 8:


@akulsr0
Copy link
Author

akulsr0 commented May 27, 2022

We need to add Provider in index.js
Step 8:

Yeah, I forgot to add, that would be after Step5

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment