Gone are the days where state can be an afterthought for your web project. Websites are handling more data live than they ever have before – but that doesn’t need to be a scary thing.
Core Components of Redux
Redux introduces a couple of new components to an application to facilitate this state management.
- Actions - Actions are used to send data from the application to the Redux store. A typical action consists of the type property and an optional payload property.
- Reducers - This is a function that accepts the current state and action as arguments and returns the updated state according to the action.
Creating a Simple Redux Application
In this section, we’ll create a simple to-do application using React and Redux.
Step 1 - Create the sample React App
Install the create-react-app package, create an app named “redux-to-do” and install Redux.
npm install -g create-react-app
npm install --save redux react-redux
Step 2 - Create the folders for Redux
Step 3 - Create the Actions
First, in our actionTypes.js. We’ll export the actionType for every action object we create:
export const CREATE_NEW_TODO = 'CREATE_NEW_TODO';
export const REMOVE_TODO = 'REMOVE_TODO';
Step 4 - Create a toDoActions.js file.
This will hold all the actions of the application, which in our case are the create and delete actions.
Step 5 - Create the Reducers
Create the toDoReducer.js file to connect the actions with the state stored in the Redux store:
Additionally, create an index.js file in the reducers folder to combine the reducers.
Step 6 - Create the Store
Create a file named configureStore.js to initialize the store and connect to the reducers.
Step 7 - Update the index.js file in the application root
We will import the react-reduce provider and store and wrap the component with the Redux store.
Step 8 - Update the App.js File
In this step, we will render the application with the specified components and connect with Redux to obtain the state of each component.
Note - The CSS classes are derived from the Bootstrap CSS framework. So you will have to link the Bootstrap stylesheet with the application. It can be done by adding the URL of the Bootstrap CSS file to the head section of the index.html file in your public folder.
Step 8 - Run the application
Use the npm run command to build and run the application. It will start the application on your default browser. Add some tasks and try it out.
That's it and you have successfully created a to-do application that manages the state via Redux!
If your local machine is slowing your development down, try Codesphere. Codesphere is an intuitive web IDE and cloud provider that lets you code, debug, and deploy all with the power of the cloud!