Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Integrating Redux with React Applications

Tech May 9 3

Dependency Installation

To manage global state, install the core state container and its React binding library:

npm install redux react-redux

Redux serves as the predictable state container, while react-redux provides the integration layer, allowing nested components to access the centralized store seamlessly.

Store Configuration

Initialize the state container within the main entry point to inject it into the component tree:

import React from 'react';
import ReactDOM from 'react-dom';
import { createStore, applyMiddleware } from 'redux';
import mainReducer from './reducers/main';
import { Provider } from 'react-redux';
import reduxThunk from 'redux-thunk';
import reduxLogger from 'redux-logger';

const globalStore = createStore(mainReducer, {}, applyMiddleware(reduxThunk, reduxLogger));

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

globalStore.subscribe(() => {
  console.log('Current State:', globalStore.getState());
});

Action Creators

Action creators encapsulate the payload and intent for state modifications.

tally.js

export function addPoints(amount) {
    return {
        type: "ADD_POINTS",
        amount
    };
}

export function deductPoints(amount) {
    return {
        type: "DEDUCT_POINTS",
        amount
    };
}

profile.js

export function updateProfile(profileData) {
    return {
        type: "UPDATE_PROFILE",
        payload: profileData,
    };
}

Reducers

Reducers dictate how the state transitions based on dispatched actions.

tally.js

const initialScore = 0;

const tallyReducer = (state = initialScore, action) => {
    switch (action.type) {
        case "ADD_POINTS":
            return state + action.amount;
        case "DEDUCT_POINTS":
            return state - action.amount;
        default:
            return state;
    }
};

export default tallyReducer;

profile.js

const defaultProfile = {
    info: {
        fullName: 'John Doe',
        gender: 'Male'
    }
};

const profileReducer = (state = defaultProfile, action) => {
    switch (action.type) {
        case "UPDATE_PROFILE":
            return { ...state, info: action.payload };
        default:
            return state;
    }
};

export default profileReducer;

main.js

import { combineReducers } from 'redux';
import tallyReducer from './tally';
import profileReducer from './profile';

const mainReducer = combineReducers({
    points: tallyReducer,
    profile: profileReducer
});

export default mainReducer;

Component Integration

Utilize the connect function to map state and dispatch actions to component props:

import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as tallyActions from './actions/tally';
import ProfileView from './components/ProfileView';

class Dashboard extends React.Component {
  render() {
    return (
      <div>
        <h1>{this.props.points}</h1>
        <button onClick={() => this.props.tallyDispatch.addPoints(10)}>
          Increase
        </button>
        <button onClick={() => this.props.tallyDispatch.deductPoints(5)}>
          Decrease
        </button>
        <ProfileView />
      </div>
    );
  }
}

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

const mapDispatchToProps = (dispatch) => {
  return {
    tallyDispatch: bindActionCreators(tallyActions, dispatch)
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(Dashboard);
Tags: ReactRedux

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.