Using Redux in ReactJS
-
Install redux and react-redux
-
Create state (src/redux/state.js)
// src/redux/state.js
export const numState = {
c: 0,
};
export const stringState = {
s: "This is some text",
};
- 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",
};
-
Create reducer (src/redux/reducer.js)
- 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; } }
- You can create multiple reducers.
- Combine them using
redux.combineReducers
import { combineReducers } from "redux"; function numReducer(state = numState, action) { ... } function stringReducer(state = stringState, action) { ... } export default combineReducers({ numReducer, stringReducer });
-
Create store (src/redux/store.js)
// src/redux/store.js
import { createStore } from "redux";
import reducer from "./reducer";
export default createStore(reducer);
- Getting Values
import { useSelector } from "react-redux";
const myState = useSelector((s) => s.numReducer);
- 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 },
});
}
We need to add Provider in index.js
Step 8: