Adding Redux to your React project


Add the necessary modules

yarn add react-redux
yarn add redux

Fix the component

import {connect} from 'react-redux';

// definition of DummyComponent here...
const mapStateToProps = (state) => ({
    count: state.count 
export default connect(mapStateToProps)(DummyComponent);

Create a DemoService class

import {createStore} from "redux";

const initialState = {
    value: 42,
    status: "Unknown",
    make: "Unknown"
   * The reducer is the only function that modifies the state
  function reducer(state = initialState, action) {
    // console.log(action);
    switch (action.type) {
      case "decrement":
        /* reurn the complete state after action! */
        return {
          ...state, /* previous state */
          value: state.value - 1,
          status: (state.value+1) > 45 ? "HOT" : "COOL"
      case "increment":
        return {
          value: state.value + 1,
          status: (state.value+1) > 45 ? "HOT" : "COOL"
      case "set_make":
        return {
          make: action.make
    return state;

  class DemoService {

  DemoService.STORE = createStore(reducer);

  export default DemoService;

Use the DemoService in the App class

import Component1 from './Component1';
import Component2 from './Component2';
import {Provider} from 'react-redux';
import DemoService from './DemoService';

const store = DemoService.STORE;

function App() {
  return (
    <Provider store={store}>

The component changes state using this.props.dispatch

decrement() {
    this.props.dispatch({ type: "decrement" });

increment() {
    this.props.dispatch({ type: "increment" });

render() {
    return (<div>
        <h1>Value is {this.props.value} </h1>
        <button onClick={this.decrement.bind(this)}>-</button>
        <button onClick={this.increment.bind(this)}>+</button>
When the store is connected, you get the dispatcher in the props. So whenever you want to change the state, call the dispatcher with an action. You can add arguments to thie object too.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.