Wednesday, July 3, 2024
HomeLanguagesReactWhat is the purpose of constants in Redux ?

What is the purpose of constants in Redux ?

In Redux, we have a lot of actions and reducers defined while making an application and managing its state from the redux. Then, constants come into the picture, it provides a way to define the type of actions and reducers at one file or one place.

The reasons to consider the constants:

  • Type of the actions and reducers are being used at two different files. Constants help to import them and use them from a single page.
  • Readability of code increases because all constants are listed in one file and gives info in one read.
  • It helps to reduce small typing issues bugs while writing.

Example of the contents:

const INCREMENT = "INCREMENT";
const DECREMENT = "DECREMENT";

Let’s create an application with react and redux to demonstrate the purpose of the constants :

Creating React Application

Step 1: Create a React application using the following command:

npx create-react-app example

Step 2: After creating your project folder i.e. example, move to it using the following command:

cd example

Now from the root directory of your project in the terminal, run the following command

npm install redux
npm install react-redux

Example: Let’s make a simple counter application with help of redux to understand the purpose of constants.

In the src folder, create two new folder components and redux. In components folder add a jsx file named Counter.jsx. In the redux folder, create a folder name actions and add a file counterActions.jsx file to it. Then in the redux folder create a folder name reducer and add a file currencyReducer.jsx. In the redux folder add store.js file.

Project Structure: The project structure will look like below:

folder structure

Below are the files that need to be modified as given in our application:

src/index.js




import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import { Provider } from "react-redux";
import appStore from "./redux/store";
  
ReactDOM.render(
    <React.StrictMode>
        <Provider store={appStore}>
            <App />
        </Provider>
    </React.StrictMode>,
    document.getElementById("root")
);


App.js




import "./App.css";
import Counter from "./components/counter";
  
function App() {
    return (
        <div
            style={{
                display: "flex",
                flexDirection: "column",
                alignItems: "center",
                justifyContent: "center",
                height: "100vh",
            }}
        >
            <Counter />
        </div>
    );
}
  
export default App;


components/Counter.jsx




import React from "react";
import { connect } from "react-redux";
import {
    incrementCount,
    decrementCount,
} from "../redux/actions/counterActions";
  
class Counter extends React.Component {
    render() {
        const { count, incrementCount, decrementCount } = this.props;
        return (
            <div>
                <button onClick={() => decrementCount()}>-</button>
                <span> {count} </span>
                <button onClick={() => incrementCount()}>+</button>
            </div>
        );
    }
}
  
const mapStateToProps = (state) => ({
    count: state,
});
  
const mapDispatchToProps = (dispatch) => ({
    decrementCount: () => dispatch(decrementCount()),
    incrementCount: () => dispatch(incrementCount()),
});
  
export default connect(mapStateToProps, mapDispatchToProps)(Counter);


actions/counterActions.jsx




const INCREMENT = "INCREMENT";
const DECREMENT = "DECREMENT";
  
const incrementCount = () => ({
    type: INCREMENT,
});
  
const decrementCount = () => {
    return {
        type: DECREMENT,
    };
};
  
export { INCREMENT, incrementCount, decrementCount, DECREMENT };


Here we have defined the two constants:

  • INCREMENT
  • DECREMENT

These two constants we are using in the actions as their types.

reducer/currencyReducer.jsx




import { INCREMENT, DECREMENT } from "../actions/counterActions";
  
const currencyReducer = (state = 0, action) => {
    switch (action.type) {
        case INCREMENT:
            return state + 1;
        case DECREMENT:
            return state - 1;
        default:
            return state;
    }
};
  
export { currencyReducer };


store.js




import { createStore } from "redux";
import { currencyReducer } from "./reducers/currencyReducer";
  
const appStore = createStore(currencyReducer);
  
export default appStore;


Step to run the application: After setting up all the files, from the terminal run the following command to start the app to run

npm start

Output: 

Output

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Dominic Rubhabha Wardslaus
Dominic Rubhabha Wardslaushttps://neveropen.dev
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments