15
Applicable React Redux example step by step from scratch
A simple example of React Redux
Step 0: Create a react app and install redux
npx create-react-app reactapp
cd reactapp
yarn add react-redux
Step 1: Create actions
ACTIONS -> INCREMENT (describes what you want to do!) it's a simple function
In src create a folder name it actions and add file named index.js
export const increment = (number) => {
return {
type: "INCREMENT",
payload: number,
};
};
export const decrement = () => {
return {
type: "DECREMENT",
};
};
Step 2: Create reducers
REDUCERS -> here an action transfer from one state to another state, it gonna modify our store.
You can have many reducers (Authentication reducer, Movielist reducer etc ...)
Create a folder called reducers
inside reducers create counter.js file
const counterReducer = (state = 0, action) => {
switch (action.type) {
case "INCREMENT":
return state + action.payload;
case "DECREMENT":
return state - 1;
default:
return state;
}
};
export default counterReducer;
inside reducers create a second reducer named isLogged.js file.
const loggedReducer = (state = false, action) => {
switch (action.type) {
case "SIGN_IN":
return !state;
default:
return state;
}
};
export default loggedReducer;
inside reducers create a index file to export them.
import counterReducer from "./counter";
import loggedReducer from "./isLogged";
import { combineReducers } from "redux";
const allReducers = combineReducers({
//you can name it anything
//counterReducer (this means counterReducer:counterReducer )
counter: counterReducer,
isLogged: loggedReducer,
});
export default allReducers;
Step 3: Create your Store
Store -> You can add your store in app.js.
You can only have one store
import React from "react";
import { useSelector, useDispatch } from "react-redux";
import { increment, decrement } from "./actions";
function App() {
const counter = useSelector((state) => state.counter);
const isLogged = useSelector((state) => state.isLogged);
const dispatch = useDispatch();
return (
<div className="App">
<h1>Counter {counter} </h1>
<button onClick={() => dispatch(increment(5))}>+</button>
<button onClick={() => dispatch(decrement())}> -</button>
{isLogged ? <h3>Valuable Information I shouldn't see</h3> : ""}
</div>
);
}
export default App;
Testing it
Option 1: check the console in inspect to see how it increments and decrements.
Option.
Option 2: Install Redux Devtool chrome extension.
https://chrome.google.com/webstore/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd?hl=en
Github repo:
https://github.com/Byusa/learn-redux
15