Core Concept You Need to Know About React

 

Article Image

REACT

INTERVIEW

Core Concept You Need to Know About React

Why use react.js

1.Reusable Components:

React provides a component based structure. Each tiny elements like button, checkbox, dropdown etc.. can be a component and the we create wrapper components composed of those smaller components. Each component decides how it should be rendered. Each component has its own internal logic.

2.Fast render with Virtual DOM

React uses virtual DOM to render the view. virtual DOM is a virtual representation of the real DOM. Each time the data changes in a react app, a new virtual DOM gets created. Creating a virtual DOM is much faster than rendering the UI inside the browser. Therefore, with the use of virtual DOM, the efficiency of the app improves.

3.SEO friendly

React allows developers to develop user interfaces that can be easily navigated in various search engines. It also allows server-side rendering, which boosts the SEO of an app.

What is JSX?

JSX stands for JavaScript XML. It allows us to write HTML inside JavaScript and place them in the DOM without using functions like appendChild( ) or createElement( ).

  • Without using JSX, we would have to create an element by the following process:
const text = React.createElement('p', {}, 'This is a text');
const container = React.createElement('div','{}',text );
ReactDOM.render(container,document.getElementById('app'));
  • Using JSX, the above code can be simplified:
const container = (

 <div>
   <p>This is a text</p>
 </div>
);
ReactDOM.render(container,document.getElementById('app'));```

As one can see in the code above, we are directly using HTML inside JavaScript*

What is the virtual DOM? How does react use the virtual DOM to render the UI?

DOM stands for 'Document Object Model'. In simple terms, it is a structured representation of the HTML elements that are present in a webpage or web-app. DOM represents the entire UI of your application

Virtual DOM is a concept where a virtual representation of the real DOM is kept inside the memory and is synced with the real DOM by a library such as ReactDOM.

Virtual Dom

Why was virtual DOM introduced?

DOM manipulation is an integral part of any web application, but DOM manipulation is quite slow when compared to other operations in JavaScript.

The efficiency of the application gets affected when several DOM manipulations are being done. Most JavaScript frameworks update the entire DOM even when a small part of the DOM changes.

For example, consider a list that is being rendered inside the DOM. If one of the items in the list changes, the entire list gets rendered again instead of just rendering the item that was changed/updated. This is called inefficient updating. To address the problem of inefficient updating, the react team introduced the concept of virtual DOM.

How does it work?

Virtual Dom

For every DOM object, there is a corresponding virtual DOM object(copy), which has the same properties.

The main difference between the real DOM object and the virtual DOM object is that any changes in the virtual DOM object will not reflect on the screen directly. Consider a virtual DOM object as a blueprint of the real DOM object. Whenever a JSX element gets rendered, every virtual DOM object gets updated.

React uses two virtual DOMs to render the user interface. One of them is used to store the current state of the objects and the other to store the previous state of the objects.

Whenever the virtual DOM gets updated, react compares the two virtual DOMs and gets to know about which virtual DOM objects were updated.

After knowing which objects were updated, react renders only those objects inside the real DOM instead of rendering the complete real DOM. This way, with the use of virtual DOM, react solves the problem of inefficient updating

Explain React state and props?

A React component can access dynamic information in two ways: props and state.

React State

Every component in react has a built-in state object, which contains all the property values that belong to that component.

In other words, the state object controls the behavior of a component. Any change in the property values of the state object leads to re-rendering of the component.

Note- State object is not available in functional components but, we can use React Hooks to add state to a functional component.

How to declare a state object?

Example:
class Car extends React.Component{
 constructor(props){
   super(props);
   this.state = {
     brand: "BMW",
     color: "black"
   }
 }
}

How to use and update the state object?

class Car extends React.Component {
 constructor(props) {
   super(props);
   this.state = {
     brand: "BMW",
     color: "Black"
   };
 }

 changeColor() {
   this.setState(prevState => {
     return { color: "Red" };
   });
 }

 render() {
   return (
     <div>
       <button onClick={() => this.changeColor()}>Change Color</button>
       <p>{this.state.color}</p>
     </div>
   );
 }
}

As one can see in the code above, we can use the state by calling this.state.propertyName and we can change the state object property using setState method.

React Props

Every react component, accepts a single object argument called props (which stands for “properties”).

These props can be passed to a component using HTML attributes.

Using props, we can pass data from one component to another.

  • While rendering a component, we can pass the props as a HTML attribute:
<Car brand="Mercedes"/>

The component receives the props:

  • In Class component:
class Car extends React.Component {
 constructor(props) {
   super(props);
   this.state = {
     brand: this.props.brand,
     color: "Black"
   };
 }
}
  • In Functional component:
function Car(props) {
  render() {
      return <h1>Name is {props.name}!</h1>;
   }
}

Note- Props are read-only. They cannot be manipulated or changed inside a component

Explain React Hooks?

Hooks are functions that let us “hook into” React state and lifecycle features from a functional component. React Hooks cannot be used in class components.

Why were Hooks introduced in React? React hooks were introduced in the 16.8 version of React. Previously, functional components were called stateless components. Only class components were used for state management and lifecycle methods.

The need to change a functional component to a class component, whenever state management or lifecycle methods were to be used, led to the development of Hooks.

Example of a hook:

useState hook: In functional components, useState hook lets us define state for a component:

function Person(props) {
 // We are declaring a state variable called name.
 // setName is a function to update/change the value of name
 let [name, setName] = useState('');
}

What are the different lifecycle methods in React?

Each component in react goes through three phases: MountingUpdating, and Unmounting.

  • Mounting :- Birth of your component
  • Update :- Growth of your component
  • Unmount :- Death of your component

React Life Cycle Methods

Common React Lifecycle Methods

  • constructor()

This is used only if you have a class-based Component and it serves the purpose of initializing the state of a Component. In case of functional Components, the useState() hook is used to do the same.

  • render()

This is the method that is responsible for inserting a Component into the DOM.

The render() method is the most used lifecycle method. This is because render() is the only required method within a class component in React.

It happens during the mounting and updating of your component.

Below is an example of a simple render() in React.

class Hello extends Component{
   render(){
      return <div>Hello {this.props.name}</div>
   }
}

A render() can also return a null if there is nothing to render for that component.

  • componentDidMount()

This is invoked after a Component is inserted into the DOM for the first time.

When component has been mounted and ready, that’s when the next React lifecycle method componentDidMount() comes in play.

componentDidMount() is called as soon as the component is mounted and ready. This is a good place to initiate API calls, if you need to load data from a remote endpoint.

componentDidMount() allows the use of setState().

  • componentDidUpdate()

This is the method invoked after re-rendering an updated Component. This method can give you the information about a Component’s previous state and previous props. This lifecycle method is invoked as soon as the updating happens. The most common use case for the componentDidUpdate() method is updating the DOM in response to prop or state changes.

You can call setState() in this lifecycle, but keep in mind that you will need to wrap it in a condition to check for state or prop changes from previous state. Incorrect usage of setState() can lead to an infinite loop.

Take a look at the example below that shows a typical usage example of this lifecycle method.

componentDidUpdate(prevProps) {
//Typical usage, don't forget to compare the props
if (this.props.userName !== prevProps.userName) {
this.fetchData(this.props.userName);
}
}

Notice in the above example that we are comparing the current props to the previous props. This is to check if there has been a change in props from what it currently is. In this case, there won’t be a need to make the API call if the props did not change.

  • componentWillUnmount()

As the name suggests this lifecycle method is called just before the component is unmounted and destroyed.

You cannot modify the component state in componentWillUnmount lifecycle.

This is where you can perform any cleanups that need to be done such as invalidating timers, canceling network requests, removing event listeners, and so on.

componentWillUnmount() {
window.removeEventListener('resize', this.resizeListener)
}

What are keys in React?

A key is a special string attribute that needs to be included when using lists of elements.

Example of a list using key:

const ids = [1,2,3,4,5];
const listElements = ids.map((id)=>{
return(
 <li key={id.toString()}>
   {id}
 </li>
 )
})

Importance of keys:-

  • Keys help react identify which elements were added, changed or removed.
  • Keys should be given to array elements for providing a unique identity for each element.
  • Without keys, React does not understand the order or uniqueness of each element.
  • With keys, React has an idea of which particular element was deleted,edited, and added.

React pure component

A React component is considered pure if it renders the same output for the same state and props. For class components like this, React provides the PureComponent base class. Class components that extend the React.PureComponent class are treated as pure components.

Pure components have some performance improvements and render optimizations since React implements the shouldComponentUpdate() method for them with a shallow comparison for props and state.

Features of React Pure Components

  • Prevents re-rendering of Component if props or state is the same
  • Takes care of “shouldComponentUpdate” implicitly
  • State and Props are Shallow Compared
  • Pure Components are more performant in certain cases

React Components re-renders in the following scenarios:

  • “setState” is called in Component
  • “props” values are updated
  • this.forceUpdate() is called

In the case of Pure Components, the React components do not re-render blindly without considering the updated values of React “props” and “state”. If updated values are the same as previous values, render is not triggered.

Thanks for reading!!!

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...