You have decided to use Redux as your state management library, now you actually have done the hard part. deciding which library to use. everything else is very easy and fast. follow along to create a todo app with redux in just 5 minutes.
The idea behind Redux
You have mainly three components store, reducer, and actions.
As Redux says,
A Store holds the whole state [tree] of your application. The only way to change the state inside it is to dispatch an action on it.
Actions are payloads of information that send data from your application to your store. They are the only source of information for the store.
we will define two actions, createItem and deleteItem.
Reducers specify how the application’s state changes in response to actions sent to the store. Remember that actions only describe what happened, but don’t describe how the application’s state changes.
we will create one reducer just like a table in sql db. there can be may according to your application.
Create a new react app using CRA(create-react-app).
npm install lodash @material-ui/core @material-ui/icons react-redux redux redux-logger
If you want to learn an efficient way to store your files, use ducks file structure. But for simplicity, we will be using simple file structure.
Create a new folder inside src named “modules”
create three files inside the folder: action.js, reducer.js, store.js
actions are simple objects with one mandatory property type. you dispatch actions from your component to send data to the state store.
Ideally, you should create another file for your action types.
create a new todo.js in a new folder inside src named “pages”. this will contain our todo list component. this example is focused on Redux so we won’t try to create component/containers. we will have our entire app in this file only.
Create the UI with a form and a list to show the tasks.
It’s time to connect our todo component with the redux store.
Open your App.js and add redux provider so all of the children can access the store.
Inside your todo.js, connect it with the store using
connect component from react-redux. add these at the end of the file in todo.js.
Now the items from store will be available in component’s props. Also the other two functions(actions) will be available in props.
Lastly, call createItem and deleteItem inside of handleSubmit and handleDelete respectively.
If you want the whole app code then it is available at this github repository.
And that’s it! Did this work for you? Please leave any questions and comments below!
Thank you for reading!
If you found this article helpful, clap! 👏👏👏.