Table of contents
This article explains ReactJS from a beginner's perspective. It is designed to guide developers who are comfortable building dynamic user interfaces with JavaScript transition into building large-scale user interfaces with ReactJS
At the end of this article, you should learn:
What is ReactJS
The problem that ReactJS solves
Declarative vs Imperative Programming
The Difference between Real DOM and Virtual DOM
Understand Single page applications
Separation of Concern
Introduction to JSX
Components, props, and states
Introduction to Hooks
Before you start
To get the most out of this article, you should be comfortable building websites with
HTML
CSS
JavaScript
Introduction
Building websites and web applications have become increasingly challenging with time. Modern web applications require complex user interfaces, and you will need to factor in business logic, structure, and data that changes constantly in the development process.
Using pure JavaScript to build modern user interfaces can be challenging. To update the front end of an application using pure JavaScript, you will need to:
Select the
DOM
nodeListen for an
event
(e.g. click of a button, submitting a form, etc) on the nodeCreate new elements that describe the user interface
Assign content to these elements.
Finally, update the DOM with the required element.
Whenever you use pure JavaScript to build the user interface, it consumes a great deal of development time and introduces a lot of bugs to our application.
ReactJS provides a solution to this problem, by allowing developers to build complex user interfaces without having to write difficult-to-understand JavaScript code and numerous DOM manipulations.
In the next section, we will explore what ReactJS is and the solution it provides.
What is ReactJS?
ReactJS is a front-end JavaScript library for building user interfaces. It lets you create complex UIs from small and isolated pieces of code called “components”.
This library has been used to build popular web applications like Facebook, PayPal, Netflix, etc.
What is unique about ReactJS?
React enables developers to create a large-scale web application that accepts data likely to change over time without the need to reload the page to view the updates. This makes the front end of apps load faster and provides a better user experience, especially on mobile devices.
Generally on websites, whenever the data changes on the server, the web client(browser) requests the server to fetch the latest information, this requires a reload of the browser to view the changes.
ReactJS avoids reloading the page whilst providing access to real-time data changes.
To understand how data changes constantly in modern web apps, let's consider the example below using the Facebook web app(since it was built with ReactJS).
For instance, your favorite influencer goes on Facebook Live, and you log in to watch the video.
Whilst watching, you liked it and proceed to read comments.
In browsing through the comments, you notice the live count, likes, comments, etc keep updating.
There was no reload of the page, however, the user interactions on the video keeps increasing.
That is ReactJS in action, data on the site is changing without reloading the page.
In the next section, we will examine the problems ReactJS solves.
The problems ReactJS Solves
Developers use tools to solve problems encountered in daily work. Knowing what problem exists and how the specified tool solves the problem will propel your knowledge about the tool significantly.
In this section, we will take a look at the problems that exist when building user interfaces and how ReactJS work out these problems.
Let's get started
Managing complex DOM interactions
Updating the UI with plain JavaScript is very verbose and complicated. You will need to give out instructions on what elements are to be created, assign content to these elements, select an element from the DOM, and then attach the newly created elements to the selected element to create an updated UI in response to an event.
Assuming you will need to go through these steps multiple times to create the UI of an eCommerce app, this will require a great deal of development time.
Also, as the DOM operations in the background increase, the app will begin to run slowly.
ReactJS is built to handle complex DOM updates and interactions.
For instance, if you are building an application that requires a lot of interaction (button clicks, submitting a form, posting, commenting, editing and deleting items, updating profiles, etc), ReactJS can be used to quickly create the user interface of the application, increasing the development speed and performance of your app
Handling higher-performance apps.
If you are building an application that requires users to be commenting on a post regularly, you will need a way to quickly update the DOM to reflect an updated UI.
You don't want to reload your app just to see the latest comment or to see the like counts go up.
ReactJs can handle this using the concept of Virtual DOM
. Whenever you render a page using React, it stores the state of the DOM tree. If there is an update to be made on the UI, React compares the previous DOM state to the current DOM and only updates the elements that have changed.
With this approach, a lot of DOM operations are minimized improving the performance of your application.
Writing scalable and easily maintainable frontend code
Traditionally, if you want to develop the UI of an application, each HTML file you create will represent the screen or page of your app.
For instance, if you are building the Home page, every required element (button, text, images, div, paragraphs, headings, etc) will be defined in that single file ( eg. index.html
).
You then link the CSS
and JavaScript
files to the index.html
.
Assuming the Home, About, and Contact pages of your app require a Navbar and footer section, you will have to write the same lines of code for the Navbar and footer in the required pages.
If you decide to change some text in the footer, the same changes will have to be made on all the pages that use the footer section
Building a web app this way introduces huge lines of code in a single file, and that makes maintaining and updating the app very tedious.
However, whenever you build the user interface of an app in React, you will slice the UI into smaller units called components
and develop each component separately.
Each component will contain all the markup and logic needed to make the app functional.
Writing code this way makes your app modular, reusable, and maintainable. If there is an error, you can quickly locate the component the error occurred in and fix it, and the changes will reflect in all the pages that use the component.
The components can also be used in different sections of the app solving the need to rewrite the entire functionality again.
For instance, if you develop a Footer
component. It can be reused on different pages of your application that require a footer.
We have learned some challenges with building a user interface with pure JavaScript and how ReactJS addresses these challenges.
In the next section, we explore declarative programming and learn how it helps build user interfaces.
Imperative vs Declarative Programming
We often use imperative programming, when building a user interface with pure JavaScript.
In imperative programming, you write the steps for how the user interface should be updated.
For instance:
Create a
div
elementCreate a
h1
elementAssign text to the
h1
Create a
button
elementAdd text to the button
Select the element with the
id
ofcontainer
Attach the
div
to the element withid
ofcontainer
to update theDOM
The steps above will contain a lot of DOM
methods just to create a div
with an h1
and button
element on the HTML document.
A declarative programming approach is recommended when building user interfaces because it can speed up the development process.
Rather than writing DOM
methods, the developer declares what to display (in this case, a div
, with and h1
tag with some text
and a button
)
Instead of having to write DOM
methods, it would be helpful if developers were able to declare what they want to display in the front end (in this case, an h1 tag with some text, and a button).
Because React is a declarative UI library, you can inform React of what the user interface should display, and React will figure out the steps to update the DOM on your behalf.
In the next section, we explore how React updates the DOM.
Difference between the Virtual DOM and Real DOM
React is built on the premise that DOM manipulation is a costly operation and should be minimized.
Using pure JavaScript to update the DOM to reflect UI changes in a large-scale application will consume more memory whenever the document is reloaded. In effect, the operation speed of the browser becomes slower due to the huge usage of memory.
For any change in the UI, the browser has to search, check, and parse the number of nodes to reflect the changes. When the number of UI changes increases, efficiency decreases, making the browser slower.
For example, if you have used JavaScript to build a Todo app that lists 20 Todo items.
Whenever you check off one item from the list, JavaScript rebuilds the entire list in the DOM. This is 19 times too much work! There was only one change, but the other nineteen were rebuilt exactly as they were
To combat this, React provides the developer with a virtual
DOM to render instead of the real
DOM.
The virtual DOM is a programming concept where an ideal or "virtual" representation of a UI is kept in memory and synced with the "real" DOM by a library such as ReactDOM
. This process is called reconciliation.
The virtual DOM is a lightweight JavaScript object that is a copy of the real DOM and the UI is rendered on the Virtual DOM instead of the real DOM.
Whenever the UI changes, React renders the entire UI in the Virtual DOM. The Virtual DOM works in these simple steps:
React uses two Virtual DOM to keep track of UI changes.
Whenever the UI or any underlying data changes, it stores the change in the new DOM whilst keeping the previous DOM
It compares both DOM and detects which part of the DOM got updated.
Once detected, it re-renders only those objects which got updated inside the Real DOM, instead of completely re-rendering the Real DOM
This increases DOM efficiency, improves browser performance, and makes the application faster to load.
Introduction to Single Page Application
In most traditional websites, the entire website loads whenever you navigate from the current page.
For instance, if you move from www.example.com
to www.example.com/about
a request is sent to the server for that resource, it returns the appropriate response and the entire website is reloaded.
On completion, certain aspects of the website may not have changed. For instance, on each page of the website, the navigation bar, sidebar, and footer will remain the same.
Because these sections remain the same, a full reload is unnecessary. This will take a long time and decrease the performance of the website
React solves this challenge with the concept of a single-page application.
A single-page application is an application that loads a single HTML page and all the necessary assets (such as JavaScript and CSS) required for the application to run.
Any interactions with the page or subsequent pages do not require a round trip to the server for a response. That means, the page is not reloaded.
You have only one single page that is loaded the first time you launch the web app. Afterward, the app will not be fully reloaded no matter where you navigate to.
The objective of a single-page application is faster transitions making the website feel more like a native app.
To detect a single-page application, you will notice that the loading icon of the browser will not reload when you move from one page to another, as opposed to traditional websites.
In building React apps, you will notice there is only one App.js
file. This file is the location for your components (sections of your applications About, Dashboard, Admin Contact pages, etc).
Is only the App.js
file that will be rendered to the DOM.
See the example below:
ReactDOM.createRoot(document.getElementById("root")).render(
<React.StrictMode>
<App />
</React.StrictMode>
);
It is this single javascript file, that helps to display the user interface of our app. All the other pages will be a component inside the App.js
and you then utilize a client-side routing tool (eg. React Router
) to navigate to the other pages
See example below
function App() {
return (
<>
<div className="app">
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/services" element={<Services />} />
</Routes>
</div>
</>
);
}
Understanding JSX
HTML, CSS, and JavaScript are the main tools for building the web.
The HTML controls the structure and content of the website
The CSS is responsible for the design
JavaScript handles the logic.
Generally, HTML, CSS, and JavaScript live in separate files and should not be mixed.
As the web became more interactive, logic increasingly decided content, making JavaScript in charge of the HTML, and introducing a concept called JSX
.
JSX stands for JavaScript XML, it allows you to write HTML inside JavaScript and place them in the DOM without using functions like appendChild()
or createElement()
. It is used in React to describe what the UI should look like.
The createElement
method enables you to create a React element and serves as an alternative to writing JSX.
The syntax is as below:
const element = createElement(type, props, ...children)
If you want to create a p
inside a div
, without using JSX
, you would have to create these elements below:
const paragraph = React.createElement('p', {}, 'This is a paragraph');
const container = React.createElement('div',{},paragraph );
ReactDOM.render(container,rootElement);
Using JSX, the above can be simplified as
const container = (
<div>
<p>This is a paragraph</p>
</div>
);
ReactDOM.render(container,rootElement);
In the code above, we are directly using HTML
inside JavaScript
.
Using this approach, you can build the user interface of your application, by nesting the HTML
structure in a JavaScript file.
See an example below:
Understanding React Components
React let you build the user interface of your application from individual pieces called Components
.
The concept of components enables you to break down the UI design of an application into smaller units and build each unit separately. Later, these units can be combined to form the desired UI.
Consider the UI of this Map application below:
We can separate the UI into smaller pieces so that we can build each unit separately.
The units are what we call components. For instance, we have the
TopNav
,Menu
,Sidebar
,Features
,Map
andMapDetails
components.
A component is a JavaScript function containing JSX
that can be rendered in the ReactDOM
to create the user interface.
It let you split your UI into reusable pieces, and think about each piece separately.
Because components are functions, they accept inputs (called props
) and return React elements that describe what should appear on the screen.
They are responsible for controlling a part of the app's UI and logic and allow developers to focus on the logic of the application, rather than the user interface.
Components are reusable. For instance, you can use the TopNav
component you have developed on any page that requires a top navigation.
They can also be nested to create a complex UI. For instance, when building the Home page of the UI above, we will nest the TopNav
, Menu
, Sidebar
, Features
, Map
, and Map Details
together.
Props vs State
Updating the UI with the State
The component keeps track of data. State
is the store that holds data or information about your component.
Because data or information in a Component changes frequently, the State
will also change to reflect the current data. Anytime State
changes, the Component
will re-render to store the latest information or data, hence updated information will be displayed in the user interface of your application.
Passing data with Props
Props
are inputs to components. In React, components use props
to communicate with each other. Parent components can pass information to their child components by giving them props.
Props are single values or objects containing a set of values that are passed to components using a naming convention similar to HTML-tag attributes and enable you to access data or information inside that component.
Using props
to pass data to a component is similar to using attributes
in HTML
elements.
In
HTML
elementsattributes
provide additional information about elementsSimilarly, in
React
,props
passes information toComponents
Attributes usually come in
name/value
pairs like<input name="value"/>
Similarly, props are written in
name/value
pair inside a component. For instance<Welcome name="Sara" />
Let's understand the differences between state and props using the analogy below.
Consider water for this analogy. There are properties and states associated with water.
Water's color and smell are examples of its properties(props). Water has no color or odor. When pure water is heated, boiled, or cooled, it remains transparent and does not smell different.
Temperature is an example of water's state. Put it in a refrigerator and cool it to 0°C and it will freeze, at 100°C it will be boiling. The state has changed from freezing to boiling.
This is the difference between state and property. Properties are inherent features of something. Properties do not change over time, like water’s color, smell, and taste.
The state can be controlled, just like controlling water temperature.
In React:
props are immutable (cannot be changed), while the state is mutable.
props are passed to the component, while the state is defined inside the component
Exploring built-in Hooks
At the core of building React apps is the usage of Hooks
Hooks are functions built into React that fire on specific events such as data changes, or component loading into the DOM.
You can either use the built-in Hooks or combine them to build your own.
Examples of built-in hooks
State Hooks
The state helps a component to keep track of information. To add state to a component, you can use any of these Hooks:
useState
: declares a state variable that you can update directlyuseReducer
: declares a state variable with the update logic inside a reducer function
Context Hooks
Context lets a component accept information from a faraway parent without passing it as props.
The benefit of context is to allow top-level components to pass some data to all components below it, no matter how nested they are avoiding prop drilling.
An example is the useContext
hook that allows you to read and sign up to a context.
Effect Hooks
Effects enable a component to connect and sync with systems outside of the React ecosystem. For instance, fetching data from an external application, widgets written using a different UI library, and other non-React code.
Examples of effect hooks:
useEffect
: connects a component to an external system.useLayoutEffect
: fires before the browser repaints the screen. You can measure the layout here.useInsertionEffect
: fires before React makes changes to the DOM. Libraries can insert dynamic CSS
Performance Hooks
You can skip unnecessary re-rendering of components and optimize performance using the following hooks:
useMemo
: allows us to “remember” a computed value between rendersuseCallback
: used when you have a component in which the child is rerendering again and again without the need
Ref Hooks
Refs enable a component to hold some data that isn't used for rendering, like a DOM
node or a timeout ID. Compared to States, updating a ref will not re-render your component.
Use the Refs hooks whenever you work with non-React systems, such as the built-in browser APIs.
Examples of ref hooks are
useRef
: lets you reference a value that's not needed for renderinguseImperativeHandle
:lets you customize the ref exposed by your component. This is rarely used.
Summary
In this article, you have learned most of the underlying concepts used in ReactJS to help build the modern user interface.
You learned what ReactJS is, how it helps solves the challenge of building complex modern user interfaces, and the different types of hooks in ReactJS applications.
Has the article helped you in your quest to build a great user interface with ReactJS?
Do you have any feedback to provide, or perhaps you want to throw more light on a section?
Please do drop your comment, and don't forget to share the article on your social handles. It would be of great help to the dev community.