10+ Fundamental Things To Approach React As Your Girlfriend!

Md Sadee Rohan
CodeX
Published in
9 min readMay 7, 2021
React

First of all, think of yourself as a lonely and uncool boy who wants a girlfriend. Then, you get to know a girl named REACT. She is so cool and appealing that you want to make her your girlfriend madly. But, you are a geek who doesn’t know how to approach her.

Well! Why I am here for? I am going to make you a perfect boyfriend for React. For this to happen, I am going to teach you some fundamentals and unique things so that you can approach her without fear and also some tricks to win her heart. So, let’s get started already!

Who is React? What is her background?

React is a JavaScript library for building user interfaces. she is the view layer for web applications. Unlike frameworks like typical Bengali girls, you don’t have to be restricted and bound to certain rules with her. You can enjoy making cool features according to your own way of thinking because she won’t bark and she is so flexible. She is always focused on one thing that is building interfaces. Without React or similar libraries, we would need to manually build UIs with native Web APIs and JavaScript and that is not as easy. But she makes it easy, fast and flexible for us. She is unique and appealing because she works with Virtual Dom that makes her more special than others.

Okay, joke time over! Now, let’s get serious about knowing about React.

Why React is Different Than Other Libraries?

React is different than other libraries that’s because it has created a common language between developers and browsers. Instead of taking actions on the DOM elements, It allows us developers to describe UIs and manage actions on the state. It’s simply the language of user interface. When any action happens to that state, React takes care of updating the UIs in the DOM based on what previous changes efficiently. React does this with Virtual Dom.

How Virtual-DOM and diffing works in React

Unlike many of its predecessors, React operates not directly on the browser’s Document Object Model (DOM) immediately, but on a virtual DOM. To understand Virtual Dom you need to know about how the actual DOM works first.

How the DOM work

When we code to develop a web application, HTML and CSS are parsed by parsers and creates a frame tree by going through some process. Then it creates a layout with styles and display it. The whole process of constructing a layout is happening under DOM process in browser. Virtual DOM do the same but virtually by React.

React Virtual Dom and Diffing process

Basically, React App virtually creates a virtual Dom when anything is changed and then it go through some diffing algorithm to compare with previous changes and do reconciliation. After the process it updates the actual DOM only at the node where there is an actual change along with it’s children. The React Virtual DOM exists entirely in-memory and is a representation of the web browser’s DOM. Because of this, when we write a React component, we’re not writing directly to the DOM, but we’re writing a virtual component that React will turn into the DOM. This is an advantage that makes React more popular.

What is JSX?

When we are into React the term JSX is unavoidable. All of our React components have a Render( ) function that specifies what the HTML output of our React component will be. JavaScript extension, or more commonly JSX, is a React extension that allows us to write JavaScript that looks like HTML. React and Browser don’t have to deal with JSX because compiler deal with that. A compiler that translates one form of syntax into another is known as a “transpiler”. To translate JSX we can use transpilers like Babel or TypeScript. For example, the jsComplete playground uses TypeScript to transpile any JSX you put into it. When you use create-react-app, the generated app will internally use Babel to transpile your JSX.

React Components

Components are like functions and independent and reusable bits of code that return HTML elements. They serve the same purpose as JavaScript functions return HTML via a render() function. Components make your code more readable and easier to work with. Simply put, a component is a JavaScript class or function that optionally accepts inputs like properties(props) and returns a React element that describes how a section of the UI should appear. There is two types of components,

  1. Class Component
  2. Functional Component

Class Component

These components are created using ES6’s class. They have some additional features like methods that handle onClick events, local state and other capabilities.

A class component in its simplest form:

class Greeting extends React.Component {
render(){
return <h1>Hi, I’m a smart component!</h1>;
}
}

Functional component

These components are simply represented by a function that optionally takes props and returns a React element to be rendered to the page. You may find functional components referred to as stateless or presentational also.

=> Functional because they are basically functions

=> Stateless because they do not hold and/or manage state

=> Presentational because all they do is output UI elements

A functional component in it’s simplest form looks something like this:

const Greeting = () => <h1>Hi, I’m a dumb component!</h1>;

Props

Props are arguments passed into React components. They are like function arguments in JavaScript and attributes in HTML.

const Welcome = (props) => {
return <h1>Hello, {props.name}</h1>;
}

const App = ()=> {
return (
<div>
<Welcome name="Sara" />
<Welcome name="Cahal" />
<Welcome name="Edite" />
</div>
);
}

As you can see, we can pass properties to child component as object and recieve it through props(properties) to use. Props is more like a network cable between components.

React Hooks

Hooks are the new feature introduced in the React 16.8 version. It allows you to use state and other React features without writing a class. It does not work inside classes. If you write a function component, and then you want to add some state to it, previously you do this by converting it to a class. But, now you can do it by using a Hook inside the existing function component. All hooks functions begin with the word “use”. Hooks are very powerful and limiteless when it comes to things you can do with them.

There is aan important type of Hook and the new way of declaring a state in React app. Hook uses useState() functional component for setting and retrieving state. Let’s understand Hook state with the following example:

import React, { useState } from 'react';const App = ()=> {   const [count, setCount] = useState(0);return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}> Click me </button>
</div>
);
}
export default App;

The Output is:

There are many more hooks like useEffect, useContext, useReducer, useRef, useMemo etc.

React Component Life-Cycle

In React, every component creation process contains various lifecycle methods. These lifecycle methods are called component’s lifecycle. These lifecycle methods are not very complicated and called at various points during a component’s life. The lifecycle of the component is divided into four phases. They are:

  1. Initial Phase
  2. Mounting Phase
  3. Updating Phase
  4. Unmounting Phase

Each phase contains some lifecycle methods that are certained to that particular phase. Let’s discuss these phases one by one:

1. Initial Phase

It is the birth phase of the lifecycle. Here, the component starts its journey on a way to the DOM. In this phase, a component contains the default Props and initial State. The initial phase only occurs once and consists of the following methods.

  • getDefaultProps()
    It is used to specify the default value of props. It is invoked before the creation of the component or any props from the parent is passed into it.
  • getInitialState()
    It is used to specify the default value of state. It is invoked before the creation of the component.

2. Mounting Phase

In this phase, the element of a component is created and inserted into the DOM. It consists of the following methods:

  • componentWillMount()
    This is invoked immediately before a component gets rendered into the DOM. In the case, when you call setState() inside this method, the component will not re-render.
  • componentDidMount()
    This is invoked immediately after a component gets rendered and placed on the DOM. Now, you can do any DOM querying operations.
  • render()
    This method is defined in each and every component. It is responsible for returning a single root HTML node element. If you don’t want to render anything, you can return a null or false value.

3. Updating Phase

It is the next phase of the lifecycle of a react component. Here, we get new Props and change State. This phase allows to handle user communication with the components parents to child order. The main aim of this phase is to ensure that the component is displaying the latest version of itself. Unlike the Birth or Death phase, this phase repeats again and again. This phase consists of the following methods.

  • componentWillRecieveProps()
    It is invoked when a component receives new props. If you want to update the state in response to prop changes, you should compare props and nextProps to perform state transition by using setState() method.
  • shouldComponentUpdate()
    It is invoked when a component decides any changes to the DOM. It allows you to control the component’s behavior of updating itself. If this method returns true, the component will update. Otherwise, the component will skip the updating.
  • componentWillUpdate()
    It is invoked just before the component updating occurs. Here, you can’t change the component state by invoking setState() method. It will not be called, if shouldComponentUpdate() returns false.
  • render()
    It is invoked to examine props and state and return one of the following types: React elements, Arrays and fragments, Booleans or null, String and Number. If shouldComponentUpdate() returns false, the code inside render() will be invoked again to ensure that the component displays itself properly.
  • componentDidUpdate()
    It is invoked immediately after the component updating occurs. In this method, you can put any code inside this which you want to execute once the updating occurs. This method is not invoked for the initial render.

4. Unmounting Phase

It is the final phase of the react component lifecycle. It is called when a component instance is destroyed and unmounted from the DOM. This phase contains only one method and is given below.

  • componentWillUnmount()
    This method is invoked immediately before a component is destroyed and unmounted permanently. It performs any necessary cleanup related task such as invalidating timers, event listener, canceling network requests, or cleaning up DOM elements. If a component instance is unmounted, you cannot mount it again.

React Optimizing Performance

Optimizing performance is an important process to consider before production of a React application. There are different ways of optimizing a React application that can enable a significant increase in speed and overall user experience for your applications. Though there are many ways you can optimize the performance but today I’ll be using 3 easy processes as example:

Use React.Fragment to Avoid Adding Extra Nodes to the DOM

Using React.Fragment will not add any additional node to the DOM and boost up some speed when it is large application. The syntax looks like this:

const Columns = () => {
return (
<React.Fragment>
<td>Hello React!</td>
<td>Hello React Again!</td>
</React.Fragment>
);
}

You can also use the short syntax <></> for declaring a Fragment.

const Columns = () => {
return (
<>
<td>Hello React!</td>
<td>Hello React Again!</td>
</>
);
}

Use Production Builds

Another way of optimizing a React app is by making sure you bundle your app for production before deploying. This can be very useful while you’re developing, but it can make your app size large and responses slower than usual. If your project is built with create-react-app, you can fix this by running “npm run build” before deploying, which will create a production-ready build of your app in a “build” folder and you can deploy after that. You can confirm if your app is in either development or production mode using the “React Developers Tool”(chrome extension for react developers)

Virtualize a Large List Using react-window

When you want to render a large table or list of data, it can slow down your app’s performance. Virtualization can help in a scenario like this with the help of some libraries like react-window and react-virtualized. They help solving this problem by rendering only the items in the list that are currently visible, which allows for efficiently rendering lists of any size.

So, these are some tricks and trips to make react your girlfriend haha!

I know this is not much but I’ll gather more information and write more understandable blog about react in future.

--

--