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:
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:
Below are the files that need to be modified as given in our application:
Here we have defined the two constants:
These two constants we are using in the actions as their types.
Step to run the application: After setting up all the files, from the terminal run the following command to start the app to run
Please Login to comment...