We now know what Redux is, we looked at the core concepts of Redux and so it is time to know about Redux App Structure to know how all these pieces fit together. Just like we learned Svelte by making a Todo Application we will also be learning about working with Redux by doing a todo application with react and Redux.
Initail Setup
First of all we need to install Redux in our application. We can do this with npm install redux
to install the redux core library but since we will be building the todo application with react it is best to install the react-redux.
$ npx create-react-app redux-todo
$ npm install react-redux
After installing all the required packages and now we will edit the App in the src
dir to make it look like a todo application and then after that we will use the Redux in it.
Todo Application
I have already built a simple Todo application with CRA and for now it contains a single Todo and nothing else. It contains a form for adding more todos. The todo right now are being stored using the useState Hook.
You can find the source code for the Todo Application in the current state on -> This <- link.
Using Redux
As we know that a redux application have a single store which stores all the state data of the application. It have reducers that are used to update the state and actions which tell the reducer what part of the state to update. Currently a todo's data in the state looks like this.
{
id: 0,
text: "First Todo",
done: false
}
The store is a list of Todos. Now we will be implementing the redux in our todo app.
Defining A Reducer
First of all we will be creating a reducer function. A reducer function is a pure function. It will not mutate the value of the store that we will be provideing it but will return us with a new store that is updated with the value action provided.
I will be creating a new file named reducer.js
in the src
directory and in the file we define a reducer function.
// reducer.js
let lastId = 0;
const reducer = (store = [], action) => {
switch (action.type) {
case "ADD_TODO":
return [
...store,
{
id: lastId + 1,
text: action.payload.text,
done: false,
},
];
case "REMOVE_TODO":
return store.filter(todo => todo.id !== action.payload.id);
}
};
Here the reducer takes store as the first argument and the action as the second argument to update the store. In the next post we will be creating a store and add implement the store in the app and make the app fully functional.