Gist of all concepts in ReactJs

Vivek Singh
6 min readNov 1, 2021

--

( Can read before an interview )

What is ReactJS?

ReactJS is a free, open-source frontend JavaScript library used to build user interfaces. It is maintained by Facebook.

How to get a React application?

  1. Add the below code before body tag in HTML -
<script>
<script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script>
</script>

2. Just use npm manager to create a boilerplate application for you -

npx create-react-app my-app
cd my-app
npm start

Code example in ReactJS :

ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('root')
);

It displays a heading saying “Hello, world!” on the page.

What is JSX ?

const element = <h1>Hello, world!</h1>;

Isn’t the syntax strange ? We do not declare variables with a HTML tag in JavaScript. So this is not JS. This is what a JSX is i.e JavaScript +XML. JSX allows us to write HTML in React.

React embraces the fact that rendering logic is inherently coupled with other UI logic: how events are handled, how the state changes over time, and how the data is prepared for display.

Now frameworks like Angular believe that the rendering logic and UI logic should be in separate files. However React team does not believe so. You can check this video on why React follows and believes that React is correct https://www.youtube.com/watch?v=x7cQ3mrcKaY&ab_channel=JSConf

You’re not required to use JSX. However JSX usage makes writing React applications easier .

Using JSX:

const myelement = <h1>John Mayer</h1>;

ReactDOM.render(myelement, document.getElementById('root'));

Without JSX :

const myelement = React.createElement('h1', {}, 'I do not use JSX!');

ReactDOM.render(myelement, document.getElementById('root'));

Do you see the extra effort in the code without JSX ? You had to write explicity React.createElement and complex parameters inside it.

With JSX you can write any valid JavaScript expressions inside curly braces { }.

const myelement = <h1>React is {5 + 5} times better with JSX</h1>;

will output React is 10 times better with JSX.

Rendering in React

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

Say that root was a parent <div> element where we wanted to show the header ‘Hello World’. So we pass the message as 1st parameter that we want to be displayed and the div html element as 2nd parameter where the message is displayed.
React elements are immutable.

Components

React components lets one break the user interface into separate pieces of individual code so that code is clear, and easier to maintain.

There are two different ways to define a component :

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

The above is called a functional Component. A major issue with functional component is that it does not have a way to define it’s local state.
However React team have made major updates(16.8) and now that is possible using HOOKS.

class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}

This is a class component.

We also have stateful and stateless component .

Stateful component has a state variable inside it(marked in Bold in below code) :

class ExampleComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
heading: "This is an Example Component!"
}

}
render() {
return (
<div>
<h1 > {this.props.welcomeMsg} < /h1>
<h2 > { this.state.heading} < /h2>
</div>);
}
}

Stateless component doesn’t have state defined inside it :

export default class App extends React.Component {
render() {
return (
<div>
<h1>Hello there!</h1>
</div>
);
}
}

State

React State is an internal store for every component. Whenever state changes the entire component is re-rendered.

In the component section I had an example explained on how to to define a state inside component. Let’s see how we can update a state :

this.setState({artist: John Mayer'});

Props

Props are values which can be sent along while calling other components. The values which are sent are read only.

Example :

function Example(props) {
return (
<div>
<UserComponent user={props.name} />
</div>
);

Many a times we may need to modify the prop values sent by a parent component to child inside the child component .This is how we can achieve this.

Controlled Components

A component which renders form elements and controls the form data using a state object defined inside a component. The elements takes values asprops and notifies changes through callbacks like onChange

import React from 'react';class App extends React.Component {
state = {
message: ''
}
updateMessage = (newText) => {
console.log(newText);
this.setState(() => ({
message: newText
}));
}
render() {
return (
<div className="App">
<div className="container">
<input type="text"
placeholder="Your message here.."
value={this.state.message}
onChange={(event) => this.updateMessage(event.target.value)}
/>
<p>the message is: {this.state.message}</p>
</div>
</div>
);
}
}

In the above example, we are maintaining a state inside the component, and passing the value and handler(which takes care of modification of state variable) while calling input.

Uncontrolled Components

A component that renders form elements and controls the form data using the HTML DOM instead of a React provided solution(i.e maintaining it’s own state). Instead of writing an event handler for all of your state updates, you use a ref to retrieve values from the DOM.

const { useRef } from 'react';

function Example () {
const inputRef = useRef(null);
return <input type="text" defaultValue="bar" ref={inputRef} />
}

Composition VS Inheritance

React Team recommends choosing Composition over Inheritance. Inheritance is a child class deriving properties from a parent. Composition is also a very well known term in Object Oriented Programming, meaning a class can reference one or more objects(different class) as instances.

Both Composition and Inheritance makes life easier for developers by giving the liberty to reuse code and write it in a clear way.

export default class Heading extends React.Component {
render () {
return (
<div>
<h1>{this.props.message}</h1>
</div>
)
}
}

In the above example, we can call Heading message = ‘Random message’ /> from different components and pass a different message every time. So React uses props to reuse a component. And calling the component like done above is what a Composition is. Inheritance will not give any advantage in React; as the way React is built, it relies on passing component and calling components inside a component.

Remember React doesn’t say that Composition is better that Inheritance in general. It is just that Composition fits better with React.

Higher Order Components

When multiple components share the same core logic, then we can use a Higher Order Component. A Higher Order Component (HOC) is a function that takes a component and returns a component.

Lifecyle in React

Lifecycle methods are a series of events which happens while creating, updating, maintaining, and destruction of a component.

React lifecycle phases :

  1. Mounting (adding nodes to the DOM)
  2. Updating (altering existing nodes in the DOM)
  3. Unmounting (removing nodes from the DOM)
  4. Error handling (verifying that your code works and is bug-free)

Each phase above has got it’s own methods which we can override to run our code at specified time during the lifecycle phases.

Check this for more info : https://blog.logrocket.com/react-lifecycle-methods-tutorial-examples/

React Hooks

Hooks are a new addition in React 16.8. React Hooks lets us use state and other important features like lifecycle methods inside a functional component. We cannot use this.state inside a function to define component because this object can be accessed from outside the function too. This is how we use hook to define a state :

import React, { useState } from ‘react’;
function Example() {
// Declare a new state variable, which we’ll call “count”
const [count, setCount] = useState(0);
return <div>{count}</div>
}
//to update count <button onClick={() => setCount(count + 1)}>
Click me
</button>

For more information check this.

Babel

Babel is a transpiler i.e it converts JSX to vanilla JavaScript. You can view babel as an intermediate step between your code and “executable” code. React also uses ES6, which is not supported by most of the browsers. Babel converts the ES6 code to a code which is compatible with the browsers.

Virtual DOM

Probably, one of the most important concepts in any frontend framework; because this is critical to the performance of the application. Whenever you update any element in DOM, there needs to be a comparison between new DOM and older DOM to check what has changed so that the updates can be reflected to the user. Problem of transforming one tree into another takes O(n3) where n is the number of elements in the tree. This time complexity is considered a state of the art approach.

However React uses it’s own implementation to compare and update those elements which have changed, and takes only O(n) time complexity. React maintains two virtual DOMs at any instant one with ‘updated state’ virtual DOM and other with ‘previous state’ virtual DOM.

Check this React article for more info : https://reactjs.org/docs/reconciliation.html

Angular and React Difference

Conclusion

We covered React in this blog. Next I will talk about Redux and how it fits in with React. Follow and hit the clap button for more blogs, and stay updated. Cheers!

--

--

Vivek Singh
Vivek Singh

Written by Vivek Singh

Software Developer. I write about Full Stack, NLP and Blockchain. Buy me a coffee - buymeacoffee.com/viveksinless

No responses yet