React Redux
React Redux
CHEAT SHEET 01
Redux Setup
were our data would be stored and to create it
Redux is a library that holds your application state in a just use the createStore function and pass the
rootReducer as parameter.
place that is globally accessible so that your application
components can directly access the data from that global Setup Redux Store redux/store.js
Installing
place, instead of you manually passing data throughout all import { createStore } from "redux";
the components. npm i redux react-redux import rootReducer from "./reducer/rootReducer";
const store = createStore(rootReducer);
OR
export default store;
yarn add redux react-redux
React Redux
import { combineReducers } from "redux"; // Redux Action
// Reducers import { addUserAction } from
import user from "./user/user.reducer"; "../Redux/reducer/user/user.action";
Reducers & Actions Root reducer really required to bundle all your seperate
const submit = () => {
dispatch(addUserAction(userData)); 2
reducers into one single object to pass on to the store. };
A simple reducer combineReducers method is used to acheve this.
return (
const INITIAL_STATE = { Redux Action <>
user: [], <button id=”submit-btn” onClick={submit}>
// Redux Action to add new user
Submit
}; export const addUserAction = ({ name, email }) => {
</button>
const userReducer = (state = INITIAL_STATE, action) => { return {
</>
switch (action.type) { type: "ADD_USER",
);
payload: { name, email, id: `${Math.random()}` },
case "ADD_USER": }
};
return {
};
...state,
An action is a simple function that would specify what type of action / Redux provides us with hooks to simplfy
user: [...state.user, action.payload], what type of operation that a reducer should perform. By returning the the dispatch process. useDispatch hook
type property the reducer will perform the action based on that type. will return the dispatch function which
};
can be used to dispatch action.
case "DELETE_USER":
Access redux store values
return {
import { useSelector } from "react-redux";
...state, const UserList = () => {
user: state.user.filter(({ id }) => id !== // Redux state
action.payload), const reduxState = useSelector(({ user }) => ({ user}));
}; return (
<>
default: Redux provides us with hooks to simplfy
<div className="d-flex mt-5 flex-wrap"> the access. useSelector hooks is used to
return { get the redux state object.
<h1>{reduxState.user.name}
...state, </div>
}; </>
} );