If you are a beginners let's start with me.
How to start
for new project you can run the below command
npx create-react-app my-app --template redux
for existing react project just run
npm i react-redux
There are three fundamental concept in redux.Also we can call 3 pillers of redux
- Store : Store will contain all of the states of our application.
Now we will start practical work.
We created a store using the CreateStore() functioin which is imported from redux. Also the CreateStore function can not take more than one Reducer. So we have used other function combineReducer().Inside the function we can put multiple reducer in an object. Then we have exported the Store file for using it in index/app file. Our store is created. Now we will move on index file. Then we will wrap the app.js file using Provider prop which is provided by react-redux.
Create An Action File
We can create multiple action file but today we will create just a single action file for simplicity. Action in redux is just a javacScript object. But we will make a function for reusing the action. Which is called action helper fucntion.
Follow the below code
Then created 2 action (addMember,removeMember) update action will be created later. Every action has two property one is type.Type is just a string used for identifying the specific action. Other is called payload. We can call it input.
Follow the code below
In this code block we created a Reducer which name is TeamReducer. We will work with team member so we created this one. We can create multiple reducer in our application. But we created one.
Reducer has been used in store as name teams. See the fig-store All of the states of TeamReducer will be stored in the teams.
Notice the TeamReducer it is taking two argument.First is initial state, second is Action. The initial is an empty array.
Now try to understand the logic.
In Home component we used the addMember action in a button at line no 32. We used dispatch functuon which is provided from react-redux.When we will use an action. We have to use the action function inside the dspatch function. Also here is an input field we are getting the value using getText function. And the text is being stored in text state follow the (20,21,22) lines. Follow this below picture
Get State From Redux
Notice the line no 25 in fig-home we get the all teamMembers form state.teams. Which are geting from redux store using useSelector. The useSelector we imported from react-redux.
useSelection function works link map() function. After getting the all members array then we use normal map(line no 30 in fig-home).
When We clicked on Remove button the The removeMember action dispatched (lin-30 fig-home). Then According to logic in TeamReducer (line 41-46 fig-reducer).A single member will be removed from state by one click.
Which happend below. One member gone by clicking Remove.