React Component Communication with Redux

Ergün Kezer
Neyasis Technology
Published in
7 min readAug 19, 2020
Image-1.Photo by Marko Pekić on Unsplash

Components are quite popular when designing applications. Because you can reuse them over and over again in your entire application. That is quite a time-saving feature for you. Of course, you can use all components in one javascript file and handle them. However, that causes lots of complexity. You can not read your code easily and maintain it whenever you need it. Can you imagine how difficult it would be to change a line of code out of 1000 lines and expect this code only affects where you intervene?

Image-2.Components

Let’s talk about Image-2. There are three components on the page. Let’s assume we don’t use components and code everything on one javascript file. We will have complex hundreds of lines of codes. For example, showing character detail is not related to the search bar or list items do not affect showing detail. As a matter of fact, main function of the red section(search bar) is searching for something. On the other hand, main function of the blue section(list) is to list items. You don’t need to use them in one place. These two components can split and communicate with each other. At this point, Redux will help us a lot. You will see how to use Redux in the rest of this article.

What is the goal?

The main goal is an orginezed, legible code which should not be hundreds of
lines in one javascript file.While you communicate components, you shouldn’t drown in the props chain. Main purpose here is to find your code easily whenever you want to change a line of your code.

Pre-requirements

The project is run on node.In case you do not have the node, you may download from the link below:

Since the catche system of yarn is quite satisfactory, I use yarn instead of npm. Because I love the cache system of yarn. It is so easy to install it.

npm install -g yarn

As a last step, create the app.

yarn create react-app ricky-and-morty

Dependencies

Welcome to the new coding world.Now,we do not have to code everything by ourselves anymore.Projects have short due times. That’s why, we need to use these packages like API calls, handle dates, component communication, etc. It gives you lots of time to save. The packages which are used in this project are introduced in the following lines. Installation command line for this packages is given below:

yarn add axios redux react-redux redux-thunk

Axios

Axios is a Javascript library used to make HTTP requests from node.js or XMLHttpRequests from the browser and it supports the Promise API. It has lots of features like transforming JSON automatically, interception of requests and responses etc.

Redux

Redux is a predictable state container for JavaScript applications and a polyvalent tool for organizing the application states. You can use Redux whole JS Frameworks and vanilla JS. There are four main concepts of Redux: Action Creator, Action, Reducer, and State.

Image-3. Modern Redux Flow Diagram

Action: Actions are plain JS object that payloads of information that send your data from the application to the store. Actions have the type and optional payload. The payload is not essential here.

Gist-1. Action

Action Creator: An action creator is a function that returns an action object. Action Creator sends action objects to reducers with the help of type (dispatch).

Gist-2. Action Creator

Reducer: The reducer is a function that takes two arguments to represent previous data and action. After that, it returns a new state.

Gist-3. Reducer

State: The central repository of all data from reducer.

React-redux

React-Redux is the React binding for Redux. It lets your React components read data from the Redux store and dispatch actions to the store to update data. There are two main concepts of React-Redux: connect and Provider.

Provider: Provider is a tag by React-Redux. It makes the Redux store available to the rest of our application. That’s why you need to wrap all the components from the top.

Gist-4. Provider

Connect: The connect() function connects a React component to a Redux store.

Gist-5. Connect

Redux-thunk

Gist-6. Redux-Thunk

Redux actions work synchronously and only return plain objects. Normally, I do not prefer using API calls into a javascript file. I want to reach the API call wherever I want. But we have a problem here. The data from API call in action
cannot received, since it does not return a plain javascript object. Let’s check Gist-6, it returns a function. due to async and await. They are recieved with ES6 so we need to use Babel which returns a function. That’s why we need to use redux-thunk with middleware. The middleware dispatches action again and makes a plain function after that.

Image-4. Middleware Diagram

and lastly lets add some UI for better looking applications.

yarn add semantic-ui-css semantic-ui-react

Project Structure

Image-5. Project Structure

Don’t worry we are so close to coding. For the starter, I want to introduce to the project structure. Before passing through the coding part, I would like to introduce project structure.The project has many folders like assets, components, pages, API, and redux. Project folder names need to be specific and they are developed by teams. You need to change someone else’s code. Neat and legible structure is a total lifesaviour. It prevents lots of mess. So lets coding :)

Code

First of all, we need to set the Redux-Store for the application. As I mentioned before, the store needs to be top of all components. That’s why I set it first called the javascript file(index.js).

Gist-7. Initialize Store

You can find lots of information in Gist-7. Now, I would like to explain what the createStore function does. The createStore allows us to create a Redux-Store and it takes two arguments(sometimes three but we don’t need it here)reducers and middleware. Reducers might be more than one. You can find much more information later in this article.After creating the Redux-Store, we need to pass it into the Provider tag like line eleven(11).

You will see a lot of variables from ‘./constants’ URL. I like to use my magic strings in one file and use them all over the application. It prevents mistyping

Now, Redux-Store generated.Let’s create the actions. Actions allow us to access the store and get the needed state.

Gist-8. Action types

There are two action types in Gist-8. listFilterAction is a basic action receives an argument and returns a plain object. On the other hand, listAction is not basic. It returns a function and dispatches it again. Normally redux doesn’t allow us to return a function. However, middleware is used with redux-thunk so we are okay :)

Time to create reducers. Reducers are our functions to keep the logic and change the state. It receives two arguments, previous state, and action. After actions return the object, redux checks the type that matches with reducer and creates a new state. You can manipulate the payload that came from the action argument. It allows you to carry your logic from JSX file to reducer. It provides less code complexity in the JSX files. You just need to call the reducer and get the wanted new state that’s all :)

After actions are trigger, redux checks whole reducers and try to find matched type. When redux finds it, it is not going to stop, no matter what redux keep looking for new matches.

Gist-10. Reducers

We are already familiar with lots of things in Gist-10. Here, you will have more information about combineReducer as I promised. In projects, developers need more information about components. One reducer is not enough. combineReducer allows us to use more than one reducer. You can get the reducer how you named in this function(combineReducer).

Time to bring all together in one JSX file.

Gist-11. AppJS

When you look at the Gist-11 you notice that is so long. However, it is the short
version. Imagine now, you put all components communication and API calls. Seventy-four lines would be more than double. As I mentioned earlier you are not working alone. Other developers may work here too. He/She is going to add some codes here too, mess will growing. Redux offers and gives you a neat and understandable project. Why not using it :)

In Gist-11, you can see how to connect function works. Connect takes two arguments here(It might be one to four too). mapStateToProps allows to you to use state from Redux-Store. It is kind of a door to open Redux-Store. mapDispatchToProps object allows you to dispatch your data and set a new state.

Wrap Up

Redux is a milestone for component communication. It helps you to manage state management all over your components. It is not only this, more neat, organizer code structure, and lots of more. For further more details, you can visit the Redux official website.

You can use the code structure from the source code. It is going to help you most of your projects. If you want to check the source code, please visit :

Thanks for reading :)

--

--