DEV Community

Cover image for Understand React Redux from scrach on one page
Serge Jabo Byusa
Serge Jabo Byusa

Posted on • Updated on

Understand React Redux from scrach on one page

Redux a popular React and React Native state management library.
Here is all component of redux in one page

npx create-react-app reactapp
Enter fullscreen mode Exit fullscreen mode

cd reactapp

yarn add react-redux
Enter fullscreen mode Exit fullscreen mode

Add this in index.js

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { createStore } from "redux";
import allReducer from "./reducers";

//ACTION  -> INCREMENT (describes what you want to do!) it's a simple function

const increment = () => {
    return {
        type: "INCREMENT",
    };
};

const decrement = () => {
    return {
        type: "DECREMENT",
    };
};

//REDUCER -> (action transfer from one state to another state, it gonna modify our store)
//You can have many reducers (Auth reducer, Movielist reducer etc ...)
const counter = (state = 0, action) => {
    switch (action.type) {
        case "INCREMENT":
            return state + 1;
        case "DECREMENT":
            return state - 1;
    }
};

//STORE  -> Globalized STATE
let store = createStore(counter);

//Display it in the console.
store.subscribe(() => console.log(store.getState()));

//DISPATCH (DISPATTCH this action to the reducer)
store.dispatch(increment());
store.dispatch(decrement());
store.dispatch(increment());

ReactDOM.render(
    <React.StrictMode>
        <App />
    </React.StrictMode>,
    document.getElementById("root")
);

reportWebVitals();

Enter fullscreen mode Exit fullscreen mode

Testing it: check the console in inspect to see how it increments and decrements.

Github Repo For more advanced way of doing it:
https://github.com/Byusa/learn-redux

This repo shows the use of redux it could be one a proper way with the store and multiple reducers their own folders.

Reference:
https://www.youtube.com/watch?v=CVpUuw9XSjY

Discussion (2)

Collapse
mohitm15 profile image
Mohit Maroliya
Collapse
minskleo profile image
Info Comment hidden by post author - thread only accessible via permalink
Andrei

This article don't have any useful information for anyone. There is nothing that can be applied to real life, it's just some usage of redux api. There is no any information about correct integrating redux with react, no best practices. There is nothing useful. Why this article was created? Better to take 1 min look at redux docs an you will get a lot more.

Some comments have been hidden by the post's author - find out more