DEV Community

Cover image for React-Redux How It's Works ?
Shubham Athawane
Shubham Athawane

Posted on • Updated on

React-Redux How It's Works ?

How Redux works with React ? Let's see, In this tutorial we trying to learn the concept of react-redux (for beginners), We will be creating a small increment - decrement application using react-redux, Which I think is best example to learn complex concepts like these, So let's start.

-———————————————

First of all create Your React App using npx create-react-app app-name and install following decencies :

npm install react-redux redux

after all installation and creating-app write in command npm start to run your application and follow the below steps : -

important note: - there is problem with numbering, So please adjust
-———————————————

  1. Create Folder inside the src called actions, and inside the action folder create file called index.js and Inside that file we will create Actions like INCREMENT / DECREMENT , basically we will called it as What kind of action to do with and write following code inside index.js file
// .actions/index.js
export const incNumber = () => {
    return {
        type:"INCREMENT"
    }
}
export const decNumber = () => {
    return {
        type:"DECREMENT"
    }
}
export const resetNumber = () => {
    return {
        type:"RESET"
    }
}
Enter fullscreen mode Exit fullscreen mode

Here in this file we have created the function which will trigged by an action using dispatch method, in this file we have created 3 functions and exported them separately using export keyword, in here inNumber() will trigger "INCREMENT" method and so on.

  1. Create another folder in src called reducers, and inside reducers folder create file upDown.js and index.js. upDown.js we will create a functions that will change the state of our application. upDown.js file will contain following code.

This file will contain How to Do scenario.

//reducer/upDown.js
    const initialState = 0;
    // It is always better to initial our state with 0 or to initialize 
    const changeTheNumber = (state = initialState, action) => {
      switch (action.type) {
        case "INCREMENT":
          return state + 1;
        case "DECREMENT":
          return state - 1;
        case "RESET":
            return state = 0;
        default:
          return state;
      }
    };

    export default changeTheNumber;
Enter fullscreen mode Exit fullscreen mode

Then inside the index.js we will import the the function ChangeTheNumber from upDown.js file and here we will use CombineReducers from redux and will create function rootReducers it is most important step , and after creating the rootReducers we'll export it, like bellow

// ..reducers/index.js
    // Imprting reducer from upDown file 
    import changeTheNumber from "./upDown";
    // Importing combineReducers object 
    import { combineReducers } from "redux";

    // Creating RootReducer 
    const rootReducer = combineReducers({
        changeTheNumber
    })

    //Exporting rootReducer
    export default rootReducer;
Enter fullscreen mode Exit fullscreen mode
  1. In this step we will create a store for our react-redux application, so we will need to install react-redux package into your application using npm install react-redux , ( ignore if you already install ) after installation write the following code inside store.js file
// src/store.js
    import { createStore } from 'redux'

    // Importing RootReducers
    import rootReducer from './reducer/index'

    //Creating Store and passing rootreducer
    const store = createStore(rootReducer, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());

    export default store;
Enter fullscreen mode Exit fullscreen mode

and we will export that store to import inside index.js to make it global store. So let's how we can make it global store in next step.

  1. Go to you index.js file from src, Here import store which we exported from store.js file and also import Provider from react-redux like below.
// index.js
    import React from "react";
    import ReactDOM from "react-dom";
    import "./index.css";
    import App from "./App";
    import reportWebVitals from "./reportWebVitals";
    import store from "./store";
    import { Provider } from "react-redux";

    store.subscribe(() => console.log(store.getState()));

    ReactDOM.render(
      <React.StrictMode>
        <Provider store={store}>
          <App />
        </Provider>
      </React.StrictMode>,
      document.getElementById("root")
    );

    reportWebVitals();
Enter fullscreen mode Exit fullscreen mode

Your index.js file will look like this, here we have wrap our App inside and Pass the store={store} as a prop

( You can use redux devtool if you want : and add following code to work with devtool , It is optional to see reducers inside browsers but makes working with reducers easy )

store.subscribe(() => console.log(store.getState()));
Enter fullscreen mode Exit fullscreen mode
  1. Final Step : Go to your app.js file and import the functions we created inside /actions/ file such as { decNumber, incNumber, resetNumber } and create a variable which will hold the state result. we use dispatch method to trigger events like dispatch( functionName() ). after all our app.js file will look like this →
    import "./App.css";
    import {useSelector, useDispatch } from 'react-redux'
    import { decNumber, incNumber, resetNumber } from "./action";

    function App() {

      const myState = useSelector((state) => state.changeTheNumber )
      const dispatch = useDispatch();

      return (
        <div className="App">
          <h2>Increment / Decrement Counter</h2>
          <h4>Using React and Redux</h4>

          <div className="quantity">
            <button className="quantity_minus" title="Decrement" onClick={() => dispatch(decNumber())}>
              <span> - </span>
            </button>
            <input
              name="quantity"
              type="text"
              className="quantity_input"
              value={myState}
            />
            <button className="quantity_plus" title="Increament" onClick={() =>dispatch(incNumber())} >
              <span> + </span>
            </button>
            <button className="quantity_plus" title="Reset Count" onClick={() =>dispatch(resetNumber())} >
              <span> Reset </span>
            </button>

          </div>
        </div>
      );
    }

    export default App;
Enter fullscreen mode Exit fullscreen mode

This is how application is looking like : -

Image description

So this is how we can implement react-redux in our react application, Hopefully you find this tutorial helpful. Thank You.

Top comments (3)

Collapse
 
kitsunekyo profile image
Alex Spieslechner

for beginners I'd recommend not following this guide, but using react redux toolkit instead. you'll save lines of code, and lots of complicated setup. its officially the recommended way of using redux

Collapse
 
shubhamathawane profile image
Shubham Athawane

Yes!

Collapse
 
nasratt profile image
Nasratullah Talash

Why would you use combineReducers for only one reducer function?