Alexander Gabriel

Apr 25, 2021

3 min read

Quick Redux Setup

Redux can be quite handy in bigger applications where you want to use more functional components than class components, avoid a surplus of hooks, and don’t want to pass state down to every component as props. In this blog I will explain how to set up Redux within your project.

Quick view of my directory

I’m going to explain Redux from the top and work my way as I pass it down in my app. Firstly, in my Redux, reducers folder I am adding in my reducer. It looks like so-

This is a Reducer

The only reason I am importing ADD_TAG and DELETE_TAG from my types folder is so that I can say ‘case ADD_TAG’ as a variable instead of ‘case ‘ADD_TAG’’ as a string. It helps a bit with management. My types simply looks like this -

In the currentTags reducer (which is a function) we are setting up our initial state here. In my example is it an empty array. The second parameter is the action. In the function, we set up a switch-case statement. I have two, ADD_TAG and DELETE_TAG.

In my index.js in the reducers folder. I have this-

I am importing all my reducers here and then combining them into the combineReducers function. This is our “store” of state, essentially, all in one place.

In my index.js in my ‘store’ folder. I have this -

It is importing the combineReducers function because in the import statement it is automatically looking for the index.js file.

Now, in our main index.js file in the src folder, we need to wrap our App component in a Provider Component to pass our store down to it.

Finally, in my components folder I have a post.js component. In this component I am importing useDispatch and useSelector from react-redux. I am also importing ADD_TAG and DELETE_TAG from my types, again, just to make them variables.

In the above example, I have a hook to set different tags. I set useDispatch() to dispatch and I use useSelector to say I want to use my currentTags reducer to check the tags. In this case, when a user clicks the IconButton it will fire off the addTag function. If tags is less than 6 in length it will dispatch the tag with the type ADD_TAG to the reducer of currentTags. It will then go through the switch-case statements and and since it is the ADD_TAG type it will perform that function (which is to add the tag to state).

This is just the quick way to to setup Redux to your React application. I plan to add a more thorough explanation of Redux in future blog posts!