Loading...
New webinar: "The Remote Job Search: My Microverse Journey" with graduate Paul Rail
Watch Now

We have launched an English school for software developers. Practice speaking and lose your fear.

Topics

In this article, I share a simple walkthrough of the popular JavaScript library, React JS, and how it works with the Virtual DOM. In addition, I share more about the state management framework, Redux, and its one-way data flow. If you prefer reading blog posts to watching videos, scroll to the bottom to see me explain these concepts in a quick 5-minute video.

Understanding React

What is React? 

React is a JavaScript library that provides you with a lot of powerful features and uses. It is very fast at showing changes on the front end and extremely reactive, hence the name, React. In simple terms, a library in programming is prewritten code outlined in terms of functions and classes that you can use.

Why use React?

When building in the front end, React helps improve the user experience since it is extremely fast whenever updates are made to the front end. As a developer, it is relatively easy to learn React and it makes your code much more maintainable since it has reusable components.

How to get started with React

A few prerequisites are essential to get started with React. You need to have Node.js and its package manager npm installed on your computer.

A quick way to start is to use the tool create-react-app. For a deeper dive, into that tool, the documentation is here.

After installing the create-react-app tool using the node package manager, run the following command;

npx create-react-app my-app-name

This command creates a starter code for a react project. It takes a long time for that template to be created and all dependencies to download. This process requires a reliable and fast internet connection. 

When you open your project folder, there is an src folder. Within this folder, one of the most important files is App.js, which is your initial React component.

React organizes bits of code into small, reusable components and containers to achieve specific tasks - much like different parts of a web page. An example of this is; the navbar, sidebar or a simple form. These components are presented in a format that looks very much like HTML, yet it is not. It is called JSX and is a JavaScript extension.

Below you can see an example of the project file structure on the left and the App.js file that is within the src folder. (Project open in VS code)

App.js file

The Virtual DOM and How React Works

Let's start by understanding the usual DOM. DOM simply stands for Document Object Model. A DOM is like a map of your user interface (UI) based on the different nodes and is represented as a tree data structure. 

This usual DOM is updated to show the viewer UI changes whenever there is a change in the page. The virtual DOM on the other hand is - as the name suggests - a virtual representation of the DOM.

The virtual DOM is the one that initially is updated when there is a change to your application state. Then, whenever a new change is made in the app, it’s like a new screenshot is taken of the virtual DOM and compared with the previous one. This goes on and on with each change. 

Eventually, all those changes are looked at, and the real DOM is updated only where necessary, instead of reloading the entire thing multiple times. A diffing algorithm similar to its name is focused on finding the differences between the two trees. According to the official documentation, when diffing two trees, React first compares the root elements. An algorithm is simply a series of distinct and finite steps taken to solve a problem. The diffing algorithm is used to compare these changes - this is what makes React faster than plain JavaScript.

If there are many DOM updates, it is expensive in regards to loading speed and application memory. That is what causes the normal DOM to be slow.

Understanding Redux

Redux is a library that helps you manage application state with one global state. That global state acts as the single source of truth for your application. 

Why Redux? Don’t we already manage the state in React?

This is a common question when learning about Redux. When React applications grow, so can the complexity, due to managing application states in all of the components.

This is where Redux comes in - to provide you with just one place where the application state is managed. This is also very useful when it comes to making updates or changes to your application.

How does one-way data flow work in Redux?

An action is just a normal JavaScript object with a type attribute. Reducers are functions that take in the state and an action as arguments. Based on the type of action, the reducer returns either the same default state or a new state.

Reducers are combined to make your application store based on your initial state. In case of any changes or updates, an action is triggered. 

Based on the type of action, the reducer decides how to update the application state. Now, the beauty of these updates is that you are never supposed to change the real state. So, you either return the default state as is or return a new state based on the action’s effect on the reducer. The state is immutable, which means it should never be mutated or changed. Think of how the Incredible Hulk turns from a simple human into a giant green monster – that’s a mutation or direct change. 

Below, you can see an example of code showing actions:

{% code-block language="js" %}
const getMealsSuccess = (meal) => ({
 type: GET_MEALS_SUCCESS,
 payload: meal,
});
const getMealsError = (error) => ({
 type: GET_MEALS_ERROR,
 payload: error,
});
const getMealDetails = (id) => ({
 type: GET_MEAL_DETAILS,
 payload: id,
});
{% code-block-end %} 

Here we have sample code showing Reducers:

{% code-block language="js" %}
import { GET_MEAL_DETAILS } from '../actions';
const initialState = {
 mealDetails: [],
};
const mealDetailsReducer = (state = initialState, action) => {
 switch (action.type) {
   case GET_MEAL_DETAILS:
     return {
       ...state,
       mealDetails: action.payload,
     };
   default:
     return state;
 }
};
export default mealDetailsReducer;
{% code-block-end %} 

It’s important to note that the parts of your application that have subscribed to - and are listening to - the changes based on the new state, are the only ones that will get updated. Only components that have been changed will be re-rendered. 

To wrap it up

React is a library that provides you with reusable components for easy maintenance, and implements a Virtual DOM to make changes to your user interface faster, to improve the user experience.

Redux is an application state management library that helps reduce complexity as your React applications grow. It has a single source of truth where the application state is stored and has a one-way data flow

Your reducers define the initial state at the beginning and place it in the store. An event like clicking a button on a web page triggers an action, which is dispatched. Based on the action’s type, the reducer either returns the default state or a new state. The components that are subscribed to listen to these changes, on those parts of the state, are updated and re-rendered.

If you prefer to watch a video walk-through of this, check out the below video.

And, to have a look at a project that uses the React library and Redux for state management, check out my YummyMeals project and if you like it, please drop a star.

What’s Next?

If you are just starting and would like to join an online school that provides a solid structure through a curated curriculum that uses modern learning techniques which combine three learning strategies; book-smarts through reading and tutorials, street-smarts through a plethora of practice projects for hands-on experience, and modelling through a supportive community of mentors, peers and eventually mentees, join me at Microverse.


We have launched an English school for software developers. Practice speaking and lose your fear.

Subscribe to our Newsletter

Get Our Insights in Your Inbox

Career advice, the latest coding trends and languages, and insights on how to land a remote job in tech, straight to your inbox.

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
We use own and third party cookies to; provide essential functionality, analyze website usages, personalize content, improve website security, support third-party integrations and/or for marketing and advertising purposes.

By using our website, you consent to the use of these cookies as described above. You can get more information, or learn how to change the settings, in our Cookies Policy. However, please note that disabling certain cookies may impact the functionality and user experience of our website.

You can accept all cookies by clicking the "Accept" button or configure them or refuse their use by clicking HERE.