React Redux Tutorial for Beginners with example

Hi Guys, In this react redux tutorial we will teach you the basic of of how Redux application works. Using Redux in React is easy when you have a simple guide. We will show a step-by-step example by creating a todo list app.

What is Redux?

Redux is an open-source JavaScript library for managing application state. It is most commonly used with libraries such as React or Angular for building user interfaces. It was created by Dan Abramov and Andrew Clark.

Install Packages

To use redux in our react project. We need two packages redux and react-redux. React-redux is a special package to allow redux in react project.

Run below two commands to install packages

npm install redux --save
npm install react-redux --save

Now we have those two package ready. Now it’s time to create a simple program

Open App.js file and create a program to incress and decress value

import React from 'react';
import './App.css';

class App extends React.Component {

  state = {
    experience: 7
  }

  onExperienceUp = () => {
    this.setState({
      experience: ++this.state.experience
    })
  }

  onExperienceDown = () => {
    this.setState({
      experience: --this.state.experience
    })
  }

  render() {
    return (
      <div className="App">
        <div>Current Expirence: {this.state.experience}</div>
        <button onClick={this.onExperienceUp}>UP</button>
        <button onClick={this.onExperienceDown}>Down</button>
      </div>
    );
  }

}

export default App;

In the above example, You will see the “7” as default experience and then you will get “UP” and “DOWN” button to increase and decrease the experience. Right now this example simple store data in current component state now we will move to Store all data on “Redux” Store to access this value everywhere.

Next, We will create store.

What is Store?

A store holds the whole state tree of your application. The only way to change the state inside it is to dispatch an action on it.

To create a store, you would need two things state and reducer. Reducer is nothing but it is a simple function. To create store. Create a new file called “reducer.js” under store folder. Below is the example reducer.js file

const initialState = {
    experience: 7
}

const reducer = (state = initialState, action) => {
    const newState = {...state};

    if(action.type === 'EXPERIENCE_UP') {
        newState.experience++;
    }
    
    if(action.type === 'EXPERIENCE_DOWN') {
        newState.experience--;
    }
    return newState;
}

export default reducer;

The “initialState” is our application state. Where all value will be store.

The “reducer” is a reducer which is able to change the ” initialState”.

Next, Let’s connect our application with “Redux”.

Now we have reducer. Remember the store has to be global. The store has to be done at highest level. And highest level of React application is “index.js”. So open the “index.js” file and do the following changes

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducer from '../src/store/reducer';

const store = createStore(reducer);


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

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

Now store is available to the entire application, Let’s see above changes

The <Provider /> makes the Redux store available to any nested components that have been wrapped in the connect() function. In the simple terms the “Provider” allows us to inject the global store.

The “createStore ” allow us to create the store.

Next, Open the App.js file and do the following changes to access the Redux store.

import React from 'react';
import './App.css';
import { connect } from 'react-redux';

class App extends React.Component {
   
  render() {
    return (
      <div className="App">
        <div>Current Experience: {this.props.experience}</div>
        <button onClick={this.props.onExperienceUp}>UP</button>
        <button onClick={this.props.onExperienceDown}>Down</button>
      </div>
    );
  }

}

const mapStateToProps = (state) => {
  return {
    experience: state.experience
  }
};

const mapDispatchToProps = ( dispatch ) => {
  return {
    onExperienceUp: () => dispatch({type: 'EXPERIENCE_UP'}),
    onExperienceDown: () => dispatch({type: 'EXPERIENCE_DOWN'}),
  }
};

export default connect(mapStateToProps, mapDispatchToProps)(App);

Now, Everything is ready, Your application will look like this

Recommended Posts

React component lifecycle

21 Comments

  1. Allan said:

    I’ve been struggling for months trying to understand the Redux store. I understood bits and pieces, and had to copy and paste code to complete assignments. Now I actually understand what is going on with Provider, store, reducer, and connect. Thank you.

    October 10, 2020
    Reply
  2. chwilówka przez internet said:

    Sprawdź ranking na chwilówka przez internet i weź szybką pożyczkę internetową lub kredyt przez internet. https://chwilowki-pozyczka.pl/

    January 6, 2021
    Reply
  3. cinayet süsü izle said:

    Wonderful work! This is the type of info that are meant to be shared across the internet. Bobbee Kenny Jeramey

    January 19, 2021
    Reply
  4. free porn said:

    A round of applause for your article. Thanks Again. Great. Josy Erin Nahamas

    January 21, 2021
    Reply
  5. dublaj said:

    I do believe all of the concepts you have offered to your post. Eugenie Johnny Kaine

    January 29, 2021
    Reply
  6. altyazili said:

    Very good information thanks so much! I love sucking dick btw hmu Rosetta Drugi Reisfield

    January 30, 2021
    Reply
  7. movie online said:

    I appreciate, result in I found exactly what I used to be having a look for. You have ended my 4 day lengthy hunt! God Bless you man. Have a nice day. Bye| Latisha Kalvin Lisetta

    January 30, 2021
    Reply
  8. dublaj said:

    I suppose that sounds and smells just about right. Yolande Berton Abel

    January 31, 2021
    Reply
  9. movie online said:

    Duis arcu tortor, suscipit eget, imperdiet nec, imperdiet iaculis, ipsum. Sed aliquam ultrices mauris. Integer ante arcu, accumsan a, consectetuer eget, posuere ut, mauris. Wilona Fitzgerald Daniell

    January 31, 2021
    Reply
  10. access said:

    After all, we should remember compellingly reintermediate mission-critical potentialities whereas cross functional scenarios. Phosfluorescently re-engineer distributed processes without standardized supply chains. Quickly initiate efficient initiatives without wireless web services. Interactively underwhelm turnkey initiatives before high-payoff relationships. Holisticly restore superior interfaces before flexible technology. Tamera Curtis Ramiah

    January 31, 2021
    Reply
  11. altyazili said:

    Hi there. I discovered your web site by the use of Google at the same time as looking for a similar matter, your site got here up. It seems good. I have bookmarked it in my google bookmarks to visit then. Latrina Kimble Quartas

    February 1, 2021
    Reply
  12. direk said:

    You made some good points there. I looked on the internet for additional information about the issue and found most people will go along with your views on this website. Kathlin Kaine Arta

    February 1, 2021
    Reply
  13. donmadan said:

    When early career researchers start publishing, they do so under the guidance of more senior researchers, who show them how to write a paper. Rosabel Mordy Ewall

    February 1, 2021
    Reply
  14. movies said:

    Way cool! Some extremely valid points! I appreciate you writing this post plus the rest of the site is also really good. Millisent Isidro Wunder

    February 1, 2021
    Reply
  15. 123movies said:

    Good way of telling, and good piece of writing to take facts on the topic of my presentation subject matter, which i am going to convey in university. Devon Laurence Frederica Ronni Elton London

    February 6, 2021
    Reply
  16. 720p said:

    With all of this great information available to you, you should have no problem turning your football skills around. Tedda Poul Rockie

    February 6, 2021
    Reply
  17. movie download said:

    Way cool! Some very valid points! I appreciate you writing this article and also the rest of the site is also really good. Kathye Town Salena

    February 6, 2021
    Reply
  18. 123movies said:

    Post writing is also a excitement, if you be acquainted with afterward you can write if not it is difficult to write. Damaris Herold Rolandson

    February 7, 2021
    Reply
  19. indirmeden said:

    Hey there! Do you know if they make any plugins to protect against hackers? Marje Brew Ursola

    February 10, 2021
    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *