Getting Started with React JS

Ibad Ahmad
13 min readMay 11, 2021

Beginners guide to Javascript most famous frontend library

Photo by Nubelson Fernandes on Unsplash

React is a remarkable JavaScript library that’s taken the development community by storm. In a nutshell, it’s made it easier for developers to build interactive user interfaces for web, mobile and desktop platforms. Today, thousands of companies worldwide are using React, including big names such as Netflix and Airbnb.

In this guide, I’ll introduce you to React and several of its fundamental concepts. We’ll get up and running quickly with the Create React App tool, then we’ll walk step-by-step through the process of building out a simple React application. By the time you’re finished, you’ll have a good overview of the basics and will be ready to take the next step on your React journey.

Why should you learn React?

I highly recommend that any Web developer has at least a basic understanding of React.

That’s because of a few reasons.

  1. React is very popular. As a developer, it’s quite likely that you’re going to work on a React project in the future. Perhaps an existing project, or maybe your team will want you to work on a brand new app based on React.
  2. A lot of tooling today is built using React at the core. Popular frameworks and tools like Next.js, Gatsby, and many others use React under the hood.
  3. As a frontend engineer, React is probably going to come up in a job interview.

Those are all good reasons, but one of the main reasons I want you to learn React is that it’s great.

It promotes several good development practices, including code reusability and component-driven development. It is fast, it is lightweight, and the way it makes you think about the data flow in your application perfectly suits a lot of common scenarios.

Prerequisites

Before beginning to learn React, it makes sense to have a basic understanding of HTML, CSS and JavaScript. It will also help to have a basic understanding of Node.js, as well as the npm package manager.

To follow along with this tutorial, you’ll need both Node and npm installed on your machine. To do this, head to the Node.js download page and grab the version you need (npm comes bundled with Node). Alternatively, you can consult our tutorial on installing Node using a version manager.

What is React?

React is a JavaScript library for building UI components. Unlike more complete frameworks such as Angular or Vue, React deals only with the view layer, so you’ll need additional libraries to handle things such as routing, state management, and so on. In this guide, we’ll focus on what React can do out of the box.

React applications are built using reusable UI components that can interact with each other. A React component can be class-based component or a so-called function component. Class-based components are defined using ES6 classes, whereas function components are basic JavaScript functions. These tend to be defined using an arrow function, but they can also use the function keyword. Class-based components will implement a render function, which returns some JSX (React’s extension of Regular JavaScript, used to create React elements), whereas function components will return JSX directly. Don’t worry if you’ve never heard of JSX, as we’ll take a closer look at this later on.

React components can further be categorized into stateful and stateless components. A stateless component’s work is simply to display data that it receives from its parent React component. If it receives any events or inputs, it can simply pass these up to its parent to handle.

A stateful component, on the other hand, is responsible for maintaining some kind of application state. This might involve data being fetched from an external source, or keeping track of whether a user is logged in or not. A stateful component can respond to events and inputs to update its state.

As a rule of thumb, you should aim to write stateless components where possible. These are easier to reuse, both across your application and in other projects.

Understanding the Virtual DOM

Before we get to coding, you need to be aware that React uses a virtual DOM to handle page rendering. If you’re familiar with jQuery, you know that it can directly manipulate a web page via the HTML DOM. In a lot of cases, this direct interaction poses few if any problems. However, for certain cases, such as the running of a highly interactive, real-time web application, performance can take quite a hit.

To counter this, the concept of the Virtual DOM (an in-memory representation of the real DOM) was invented, and is currently being applied by many modern UI frameworks including React. Unlike the HTML DOM, the virtual DOM is much easier to manipulate, and is capable of handling numerous operations in milliseconds without affecting page performance. React periodically compares the virtual DOM and the HTML DOM. It then computes a diff, which it applies to the HTML DOM to make it match the virtual DOM. This way, React ensures that your application is rendered at a consistent 60 frames per second, meaning that users experience little or no lag.

Start a Blank React Project

As per the prerequisites, I assume you already have a Node environment set up, with an up-to-date version of npm (or optionally Yarn).

Next, we’re going to build our first React application using Create React App, an official utility script for creating single-page React applications.

Let’s install this now:

npm i -g create-react-app

Then use it to create a new React app.

create-react-app react_intro

Depending on the speed of your internet connection, this might take a while to complete if this is your first time running the create-react-app command. A bunch of packages get installed along the way, which are needed to set up a convenient development environment — including a web server, compiler and testing tools.

If you’d rather not install too many packages globally, you can also npx, which allows you to download and run a package without installing it:

npx i -g create-react-app react_intro

Running either of these commands should output something similar to the following:

Once the project setup process is complete, execute the following commands to launch your React application:

cd react_intro
npm start

You should see the following output:

Your default browser should launch automatically, and you should get a screen like this:

Introducing JSX Syntax

Defined by the React docs as a “syntax extension to JavaScript”, JSX is what makes writing your React components easy. Using JSX we can pass around HTML structures, or React elements as if they were standard JavaScript values.

Here’s a quick example:

import React from 'react';export default function App() {
const message = <h1>I'm a heading</h1>; //JSX FTW!
return ( message );
}

Notice the line const message = <h1>I'm a heading</h1>;. That’s JSX. If you tried to run that in a web browser, it would give you an error. However, in a React app, JSX is interpreted by a transpiler, such as Babel, and rendered to JavaScript code that React can understand.

Note: you can learn more about JSX in our tutorial “An Introduction to JSX”.

In the past, React JSX files used to come with a .jsx file extension. Nowadays, the Create React App tool generates React files with a .js file extension. While the .jsx file extension is still supported, the maintainers of React recommend using .js. However, there’s an opposing group of React developers, including myself, who prefer to use the .jsx extension, for the following reasons:

  • In VS Code, Emmet works out of the box for .jsx files. You can, however, configure VS Code to treat all .js files as JavaScriptReact to make Emmet work on those files.
  • There are different linting rules for standard JavaScript and React JavaScript code.

However, for this tutorial, I’ll abide by what Create React App gives us and stick with the .js file ending.

Hello, World! in React

Let’s get down to writing some code. Inside the src folder of the newly created react_intro , create an index.js file and add the following code:

import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(<h1>Hello World</h1>, document.getElementById('root'));

Start the development server again using npm start or yarn start. Your browser should display the following content:

This is the most basic “Hello World” React example. The index.js file is the root of your project where React components will be rendered. Let me explain how the code works:

  • Line 1: The React package is imported to handle JSX processing.
  • Line 2: The ReactDOM package is imported to render the root React component.
  • Line 3: Call to the render function, passing in:
  • <h1>Hello World</h1>: a JSX element
  • document.getElementById('root'): an HTML container (the JSX element will be rendered here).

The HTML container is located in the public/index.html file. On line 31, you should see <div id="root"></div>. This is known as the root DOM node because everything inside it will be managed by the React virtual DOM.

While JSX does look a lot like HTML, there are some key differences. For example, you can’t use a class attribute, since it’s a JavaScript keyword. Instead, className is used in its place. Also, events such as onclick are spelled onClick in JSX. Let’s now modify our Hello World code:

const element = <div>Hello World</div>;
ReactDOM.render(element, document.getElementById('root'));

I’ve moved the JSX code out into a constant variable named element. I’ve also replaced the h1 tags with div tags. For JSX to work, you need to wrap your elements inside a single parent tag.

Managing state in React

Every React component can have its own state. What do we mean by state?The state is the

set of data that is managed by the component.

Think about a form, for example. Each individual input element of the form is responsible for managing its state: what is written inside it.

A button is responsible for knowing if it’s being clicked, or not. If it’s on focus.

A link is responsible for knowing if the mouse is hovering over it.

In React, or in any other components-based framework/library, all our applications are based on and make heavy use of components’ state.

We manage state using the useState utility provided by React. It's technically a hook (you don't need to know the details of hooks right now, but that's what it is).

You import useState from React in this way:

import React, { useState } from 'react'

Calling useState(), you will get back a new state variable, and a function that we can call to alter its value.

useState() accepts the initial value of the state item and returns an array containing the state variable, and the function you call to alter the state.

Example:

const [count, setCount] = useState(0)

This is important. We can’t just alter the value of a state variable directly. We must call its modifier function. Otherwise the React component will not update its UI to reflect the changes of the data.

Calling the modifier is the way we can tell React that the component state has changed.

The syntax is a bit weird, right? Since useState() returns an array we use array destructuring to access each individual item, like this: const [count, setCount] = useState(0)

Here’s a practical example:

import { useState } from 'react'const Counter = () => {
const [count, setCount] = useState(0)
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
)
}
ReactDOM.render(<Counter />, document.getElementById('app'))

You can add as many useState() calls as you want, to create as many state variables as you want:

const [count, setCount] = useState(0)
const [anotherCounter, setAnotherCounter] = useState(0)

Component Props in React

We call props the initial values passed to a component.

We previously created a WelcomeMessage component

function WelcomeMessage() {
return <p>Welcome!</p>
}

and we used it like this:

<WelcomeMessage />

This component does not have any initial value. It does not have props.

Props can be passed as attributes to the component in the JSX:

<WelcomeMessage myprop={'somevalue'} />

and inside the component we receive the props as arguments:

function WelcomeMessage(props) {
return <p>Welcome!</p>
}

It’s common to use object destructuring to get the props by name:

function WelcomeMessage({ myprop }) {
return <p>Welcome!</p>
}

Now that we have the prop, we can use it inside the component. For example we can print its value in the JSX:

function WelcomeMessage({ myprop }) {
return <p>{myprop}</p>
}

Curly brackets here have various meanings. In the case of the function argument, curly brackets are used as part of the object destructuring syntax.

Then we use them to define the function code block, and finally in the JSX to print the JavaScript value.

Passing props to components is a great way to pass values around in your application.

A component either holds data (has state) or receives data through its props.

We can also send functions as props, so a child component can call a function in the parent component.

A special prop is called children. That contains the value of anything that is passed between the opening and closing tags of the component, for example:

<WelcomeMessage> Here is some message </WelcomeMessage>

In this case, inside WelcomeMessage we could access the value Here is some message by using the children prop:

function WelcomeMessage({ children }) {
return <p>{children}</p>
}

Data flow in a React application

In a React application, data typically flows from a parent component to a child component, using props as we saw in the previous section:

<WelcomeMessage myprop={'somevalue'} />

If you pass a function to the child component, you can however change the state of the parent component from a child component:

const [count, setCount] = useState(0)<Counter setCount={setCount} />

Inside the Counter component we can now grab the setCount prop and call it to update the count state in the parent component, when something happens:

function Counter({ setCount }) {
//...
setCount(1) //...
}

You need to know that there are more advanced ways to manage data, which include the Context API and libraries like Redux. But those introduce more complexity, and 90% of the times using those 2 ways I just explained are the perfect solution.

Handling user events in React

React provides an easy way to manage events fired from DOM events like clicks, form events, and more.

Let’s talk about click events, which are pretty simple to digest.

You can use the onClick attribute on any JSX element:

<button
onClick={(event) => {
/* handle the event */
}}
>
Click here
</button>

When the element is clicked, the function passed to the onClick attribute is fired.

You can define this function outside of the JSX:

const handleClickEvent = (event) => {
/* handle the event */
}
function App() {
return <button onClick={handleClickEvent}>Click here</button>
}

When the click event is fired on the button, React calls the event handler function.

React supports a vast amount of types of events, like onKeyUp, onFocus,onChange, onMouseDown, onSubmit and many more.

Lifecycle events in a React component

So far we’ve seen how to manage state with the useState hook.

There’s another hook I want to introduce in this book: useEffect.

The useEffect hook allows components to have access to the lifecycle events of a component.

When you call the hook, you pass it a function. The function will be run by React when the component is first rendered, and on every subsequent re-render/update.

React first updates the DOM, then calls any function passed to useEffect().

All without blocking the UI rendering, even on blocking code.

Here is an example:

const { useEffect, useState } = Reactconst CounterWithNameAndSideEffect = () => {
const [count, setCount] = useState(0)
useEffect(() => {
console.log(`You clicked ${count} times`)
})
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
)
}

Since the useEffect() function is run on every subsequent re-render/update of the component, we can tell React to skip it, for performance purposes. We do this by adding a second parameter which is an array that contains a list of state variables to watch for.

React will only re-run the side effect if one of the items in this array changes.

useEffect(() => {
console.log(`Hi ${name} you clicked ${count} times`)
}, [name, count])

Similarly, you can tell React to only execute the side effect once (at mount time), by passing an empty array:

useEffect(() => {
console.log(`Component mounted`)
}, [])

You migth find yourself using this option a lot.

useEffect() is great for adding logs, accessing 3rd party APIs, and much more.

Where to go from here

Mastering the topics explained in this article is a great step towards your goal of learning React.

I want to give you some pointers now, because it’s easy to get lost in the sea of tutorials and courses about React.

What should you learn next?

Learn more theory about the Virtual DOM, writing declarative code, unidirectional data flow, immutability, composition.

Start building some simple React applications. For example build a simple counter or a interact with a public API.

Learn how to perform conditional rendering, how to perform loops in JSX, how to use the React Developer Tools.

Learn how to apply CSS in a React application, with plain CSS or Styled Components.

Learn how to manage state using the Context API, useContext and Redux.

Learn how to interact with forms.

Learn how to use React Router.

Learn how to test React applications.

Learn an application framework built on top of React, like Gatsby or Next.js.

Most of all, make sure you practice by building sample applications to apply everything you’ve learned.

Photo by Etienne Girardet on Unsplash

Conclusion

And that’s the lot!. Hope you all find this article useful in some way. I would love to hear your thoughts and feedback on this.

--

--