Saturday, February 5, 2022

React Interview Questions


 

React Interview Questions

1.  Differentiate between Real DOM and Virtual DOM?

        

Real DOM

Virtual  DOM

1. It updates slow.

1. It updates faster.

2. Can directly update HTML.

2. Can’t directly update HTML.

3. Creates a new DOM if element updates.

3. Updates the JSX if element updates.

4. DOM manipulation is very expensive.

4. DOM manipulation is very easy.

5. Too much of memory wastage.

5. No memory wastage



2. What is React?

  • React is a front-end JavaScript library developed by Facebook in 2011.
  • It follows the component based approach which helps in building reusable UI components.
  • It is used for developing complex and interactive web and mobile UI.
  • Even though it was open-sourced only in 2015, it has one of the largest communities supporting it.

3. What are the features of React? 

Major features of React are listed below:

       i.            It uses the virtual DOM instead of the real DOM.

    ii.            It uses server-side rendering.

  iii.            It follows uni-directional data flow or data binding.




4. List some of the major advantages of React.

Some of the major advantages of React are:

       i.            It increases the application’s performance

    ii.            It can be conveniently used on the client as well as server side

  iii.            Because of JSX, code’s readability increases

  iv.            React is easy to integrate with other frameworks like Meteor, Angular, etc

     v.            Using React, writing UI test cases become extremely easy

5. What are the limitations of React?

Limitations of React are listed below:

       i.            React is just a library, not a full-blown framework

    ii.            Its library is very large and takes time to understand

  iii.            It can be little difficult for the novice programmers to understand

  iv.            Coding gets complex as it uses inline templating and JSX

6. What is JSX?

JSX is a shorthand for JavaScript XML. This is a type of file used by React which utilizes the expressiveness of JavaScript along with HTML like template syntax. This makes the HTML file really easy to understand. This file makes applications robust and boosts its performance. Below is an example of JSX:

render(){ 
return(
<div>
  <h1>Hello World from Edureka!!</h1>
</div>
); 
}


7. What do you understand by Virtual DOM? Explain its works.

A virtual DOM is a lightweight JavaScript object which originally is just a copy of the real DOM. It is a node tree that lists the elements, their attributes and content as Objects and their properties. React’s render function creates a node tree out of the React components. It then updates this tree in response to the mutations in the data model which is caused by various actions done by the user or by the system.
This Virtual DOM works in three simple steps.

1.      Whenever any underlying data changes, the entire UI is re-rendered in Virtual DOM representation.



2.     Then the difference between the previous DOM representation and the new one is calculated.








3.     Once the calculations are done, the real DOM will be updated with only the things that have actually changed. 










8. Why can’t browsers read JSX?

Browsers can only read JavaScript objects but JSX in not a regular JavaScript object. Thus to enable a browser to read JSX, first, we need to transform JSX file into a JavaScript object using JSX transformers like Babel and then pass it to the browser.

9. How different is React’s ES6 syntax when compared to ES5?

Syntax has changed from ES5 to ES6 in the following aspects:

       i.            require vs import


// ES5
var React = require('react');

// ES6
import React from 'react';

    ii.           export vs exports

  iii.            component and function


// ES5
var MyComponent = React.createClass({
    render: function () {
        return
        <h3>Hello Edureka!</h3>
    }
});


// ES6
class MyComponent extends React.Component {
    render() {
        return
        <h3>Hello Edureka!</h3>
    }
}

  iv.            props

       v.            state

10. How is React different from Angular?

TOPIC

REACT

ANGULAR

1. ARCHITECTURE

Only the View of MVC

Complete MVC

2. RENDERING

Server-side rendering

Client-side rendering

3. DOM

Uses virtual DOM

Uses real DOM

4. DATA BINDING

One-way data binding

Two-way data binding

5. DEBUGGING

Compile time debugging

Runtime debugging

6. AUTHOR

Facebook

Google

11. “In React, everything is a component.” Explain.

Components are the building blocks of a React application’s UI. These components split up the entire UI into small independent and reusable pieces. Then it renders each of these components independent of each other without affecting the rest of the UI.

12. What is the purpose of render() in React.

Each React component must have a render() mandatorily. It returns a single React element which is the representation of the native DOM component. If more than one HTML element needs to be rendered, then they must be grouped together inside one enclosing tag such as <form>, <group>,<div> etc. This function must be kept pure i.e., it must return the same result each time it is invoked.

13. How can you embed two or more components into one?

We can embed components into one in the following way:

class MyComponent extends React.Component {
    render() {
        return (
            <div>
                <h1>Hello</h1>
                <Header />
            </div>
        );
    }
}

class Header extends React.Component {
    render() {
        return
        <h1>Header Component</h1>
    };
}

ReactDOM.render(
    <MyCoponent />, document.getElementById('content')
);


14. What is Props?

Props is the shorthand for Properties in React. They are read-only components which must be kept pure i.e. immutable. They are always passed down from the parent to the child components throughout the application. A child component can never send a prop back to the parent component. This help in maintaining the unidirectional data flow and are generally used to render the dynamically generated data.

15. What is a state in React and how is it used?

States are the heart of React components. States are the source of data and must be kept as simple as possible. Basically, states are the objects which determine components rendering and behavior. They are mutable unlike the props and create dynamic and interactive components. They are accessed via this.state().

16. Differentiate between states and props.

States vs Props

Conditions

State

Props

1. Receive initial value from parent component

Yes

Yes

2. Parent component can change value

No

Yes

3. Set default values inside component

Yes

Yes

4. Changes inside component

Yes

No

5. Set initial value for child components

Yes

Yes

6. Changes inside child components

No

Yes

17. How can you update the state of a component?

State of a component can be updated using this.setState().


class MyComponent extends React.Component {
    constructor() {
        super();
        this.state = {
            name: 'Maxx',
            id: '101'
        }
    }
    render() {
        setTimeout(() => { this.setState({ name: 'Jaeha', id: '222' }) }, 2000)
        return (
            <div>
                <h1>Hello {this.state.name}</h1>
                <h2>Your Id is {this.state.id}</h2>
            </div>
        );
    }
}
ReactDOM.render(
    <MyComponent />, document.getElementById('content')
);

18. What is arrow function in React? How is it used?

Arrow functions are more of brief syntax for writing the function expression. They are also called ‘fat arrow‘ (=>) the functions. These functions allow to bind the context of the components properly since in ES6 auto binding is not available by default. Arrow functions are mostly useful while working with the higher order functions.


//General way
render() {
    return (
        <MyInput onChange={this.handleChange.bind(this)} />
    );
}

//With Arrow Function
render() {
    return (
        <MyInput onChange={(e) => this.handleOnChange(e)} />
    );
}


19. Differentiate between stateful and stateless components.

Stateful vs Stateless

Stateful Component

Stateless Component

1. Stores info about component’s state change in memory

1. Calculates the internal state of the components

2. Have authority to change state

2. Do not have the authority to change state

3. Contains the knowledge of past, current and possible future changes in state

3. Contains no knowledge of past, current and possible future state changes

4. Stateless components notify them about the requirement of the state change, then they send down the props to them.

4. They receive the props from the Stateful components and treat them as callback functions.

20. What are the different phases of React component’s lifecycle?

There are three different phases of React component’s lifecycle:

       i.            Initial Rendering Phase: This is the phase when the component is about to start its life journey and make its way to the DOM.

    ii.            Updating Phase: Once the component gets added to the DOM, it can potentially update and re-render only when a prop or state change occurs. That happens only in this phase.

  iii.            Unmounting Phase: This is the final phase of a component’s life cycle in which the component is destroyed and removed from the DOM.

 

21. Explain the lifecycle methods of React components in detail.

Some of the most important lifecycle methods are:

       i.            componentWillMount()  Executed just before rendering takes place both on the client as well as server-side.

    ii.            componentDidMount()  Executed on the client side only after the first render.

  iii.            componentWillReceiveProps() – Invoked as soon as the props are received from the parent class and before another render is called.

  iv.            shouldComponentUpdate()  Returns true or false value based on certain conditions. If you want your component to update, return true else return false. By default, it returns false.

     v.            componentWillUpdate() – Called just before rendering takes place in the DOM.

  vi.            componentDidUpdate()  Called immediately after rendering takes place.

vii.            componentWillUnmount() – Called after the component is unmounted from the DOM. It is used to clear up the memory spaces.

22. What is an event in React?

In React, events are the triggered reactions to specific actions like mouse hover, mouse click, key press, etc. Handling these events are similar to handling events in DOM elements. But there are some syntactical differences like:

       i.            Events are named using camel case instead of just using the lowercase.

    ii.            Events are passed as functions instead of strings.

The event argument contains a set of properties, which are specific to an event. Each event type contains its own properties and behavior which can be accessed via its event handler only.

23. How do you create an event in React?

class Display extends React.Component {
    show(evt) {
        // code  
    },
    render() {
        // Render the div with an onClick prop (value is a function)        
        return (
            <div onClick={this.show}>Click Me!</div>
        );
    }
};

24. What are synthetic events in React?

Synthetic events are the objects which act as a cross-browser wrapper around the browser’s native event. They combine the behavior of different browsers into one API. This is done to make sure that the events show consistent properties across different browsers.

25. What do you understand by refs in React?

Refs is the short hand for References in React. It is an attribute which helps to store a reference to a particular React element or component, which will be returned by the components render configuration function. It is used to return references to a particular element or component returned by render(). They come in handy when we need DOM measurements or to add methods to the components.


class ReferenceDemo extends React.Component {
    display() {
        const name = this.inputDemo.value;
        document.getElementById('disp').innerHTML = name;
    }
    render() {
        return (

            <div>
                Name: <input type="text" ref={input => this.inputDemo = input} />
                <button name="Click" onClick={this.display}>Click</button>
                <h2>Hello <span id="disp"></span> !!!</h2>
            </div>
        );
    }
}

26. List some of the cases when you should use Refs.

Following are the cases when refs should be used:

  • When you need to manage focus, select text or media playback
  • To trigger imperative animations
  • Integrate with third-party DOM libraries

27. How do you modularize code in React?

We can modularize code by using the export and import properties. They help in writing the components separately in different files.


//ChildComponent.jsx
export default class ChildComponent extends React.Component {
    render() {
        return (
            <div>
                <h1>This is a child component</h1>
            </div>
        );
    }
}

//ParentComponent.jsx
import ChildComponent from './childcomponent.js';
class ParentComponent extends React.Component {
    render() {
        return (
            <div>
                <App />
            </div>
        );
    }
}

28. How are forms created in React?

React forms are similar to HTML forms. But in React, the state is contained in the state property of the component and is only updated via setState(). Thus the elements can’t directly update their state and their submission is handled by a JavaScript function. This function has full access to the data that is entered by the user into a form.


handleSubmit(event) {
    alert('A name was submitted: ' + this.state.value);
    event.preventDefault();
}

render() {
    return (
        <form onSubmit={this.handleSubmit}>
            <label>
                Name:
                <input type="text" value={this.state.value}
                        onChange={this.handleSubmit} />
            </label>
            <input type="submit" value="Submit" />
        </form>
    );
}

29. What do you know about controlled and uncontrolled components?

Controlled vs Uncontrolled Components

Controlled Components

Uncontrolled Components

1. They do not maintain their own state

1. They maintain their own state

2. Data is controlled by the parent component

2. Data is controlled by the DOM

3. They take in the current values through props and then notify the changes via callbacks

3. Refs are used to get their current values

30. What are Higher Order Components(HOC)?

Higher Order Component is an advanced way of reusing the component logic. HOC are custom components which wrap another component within it. They can accept any dynamically provided child component but they won’t modify or copy any behavior from their input components. You can say that HOC are ‘pure’ components.

Higher-order components or HOC is the advanced method of reusing the component functionality logic. It simply takes the original component and returns the enhanced component.

Syntax:

const EnhancedComponent = higherOrderComponent(OriginalComponent);

Reason to use Higher-Order component:

  • Easy to handle
  • Get rid of copying the same logic in every component
  • Makes code more readable
Example 1

import React from 'react' const EnhancedComponent = (OriginalComponent) => { class NewComponent extends React.Component { // Logic here render() { // Pass the callable props to Original component return <OriginalComponent name="GeeksforGeeks" /> } } // Returns the new component return NewComponent } export default EnhancedComponent;



import React from "react";
import "./App.css"
import EnhancedComponent from './Name'

class App extends React.Component {
render() {
// Call the props from originalComponent
return <h1>{this.props.name}</h1>
}
}

// Passed the originalcomponent
export default EnhancedComponent(App);


Output: Here, we pass the name as a prop with the value for calling out from different components.

GeeksforGeeks

Example 2: In this example let’s implement some logic. Let’s make a counter app. In HighOrder.js, we pass the handleclick and show props for calling the functionality of the component.


import React from 'react'

const EnhancedComponent = (OriginalComponent) => {
class NewComponent extends React.Component {

constructor(props) {
super(props);
// Set initial count to be 0
this.state = { count: 0 };
}

handleClick = () => {
// Incrementing the count
this.setState({ count: this.state.count + 1 });
}

render() {

// passed a handleclick and count in the originalComponent
// as a props for calling and adding the functionality
return <OriginalComponent
handleclick={this.handleClick}
show={this.state.count} />
}
}
// Returns the new component
return NewComponent
}
// Export main Component
export default EnhancedComponent



import React from 'react'
import "./App.css"
// importing HighOrder file
import EnhancedComponent from './HighOrder'

class App extends React.Component {
render() {
// Destructuring the props
const { show, handleclick } = this.props

// Calling out the props
return <button onClick={handleclick}>{show}
</button>
}
}


export default EnhancedComponent(App);

31. What can you do with HOC?

HOC can be used for many tasks like:

  • Code reuse, logic and bootstrap abstraction
  • Render High jacking
  • State abstraction and manipulation
  • Props manipulation

32. What are Pure Components?

Based on the concept of purity in functional programming paradigms, a function is said to be pure if it meets the following two conditions:

  • Its return value is only determined by its input values
  • Its return value is always the same for the same input values

A React component is considered pure if it renders the same output for the same state and props. For this type of class component, 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.

33. What is the significance of keys in React?

Keys are used for identifying unique Virtual DOM Elements with their corresponding data driving the UI. They help React to optimize the rendering by recycling all the existing elements in the DOM. These keys must be a unique number or string, using which React just reorders the elements instead of re-rendering them. This leads to increase in application’s performance.

React Redux – React Interview Questions

34. What were the major problems with MVC framework?

Following are some of the major problems with MVC framework:

  • DOM manipulation was very expensive
  • Applications were slow and inefficient
  • There was huge memory wastage
  • Because of circular dependencies, a complicated model was created around models and views

35. Explain Flux.

Flux is an architectural pattern which enforces the uni-directional data flow. It controls derived data and enables communication between multiple components using a central Store which has authority for all data. Any update in data throughout the application must occur here only. Flux provides stability to the application and reduces run-time errors.



36. What is Redux?

Redux is one of the most trending libraries for front-end development in today’s marketplace. It is a predictable state container for JavaScript applications and is used for the entire applications state management. Applications developed with Redux are easy to test and can run in different environments showing consistent behavior.

37. What are the three principles that Redux follows?

       i.            Single source of truth: The state of the entire application is stored in an object/ state tree within a single store. The single state tree makes it easier to keep track of changes over time and debug or inspect the application.

    ii.            State is read-only: The only way to change the state is to trigger an action. An action is a plain JS object describing the change. Just like state is the minimal representation of data, the action is the minimal representation of the change to that data. 

  iii.            Changes are made with pure functions: In order to specify how the state tree is transformed by actions, you need pure functions. Pure functions are those whose return value depends solely on the values of their arguments.


38. What do you understand by “Single source of truth”?

Redux uses ‘Store’ for storing the application’s entire state at one place. So all the component’s state are stored in the Store and they receive updates from the Store itself. The single state tree makes it easier to keep track of changes over time and debug or inspect the application.











39. List down the components of Redux.

Redux is composed of the following components:

       i.            Action – It’s an object that describes what happened.

    ii.            Reducer –  It is a place to determine how the state will change.

  iii.            Store – State/ Object tree of the entire application is saved in the Store.

  iv.            View – Simply displays the data provided by the Store.

In case you are facing any challenges with these React interview questions, please comment on your problems in the section below.

40. Show how the data flows through Redux?








41. How are Actions defined in Redux?

Actions in React must have a type property that indicates the type of ACTION being performed. They must be defined as a String constant and you can add more properties to it as well. In Redux, actions are created using the functions called Action Creators. Below is an example of Action and Action Creator:


function addTodo(text) {
    return {
             type: ADD_TODO,    
              text    
 }
}
42. Explain the role of Reducer.

Reducers are pure functions which specify how the application’s state changes in response to an ACTION. Reducers work by taking in the previous state and action, and then it returns a new state. It determines what sort of update needs to be done based on the type of the action, and then returns new values. It returns the previous state as it is, if no work needs to be done.

43. What is the significance of Store in Redux?

A store is a JavaScript object which can hold the application’s state and provide a few helper methods to access the state, dispatch actions and register listeners. The entire state/ object tree of an application is saved in a single store. As a result of this, Redux is very simple and predictable. We can pass middleware to the store to handle the processing of data as well as to keep a log of various actions that change the state of stores. All the actions return a new state via reducers.

44. How is Redux different from Flux?

Flux vs Redux

Flux

Redux

1. The Store contains state and change logic

1. Store and change logic are separate

2. There are multiple stores

2. There is only one store

3. All the stores are disconnected and flat

3. Single store with hierarchical reducers

4. Has singleton dispatcher

4. No concept of dispatcher

5. React components subscribe to the store

5. Container components utilize connect

6. State is mutable

6. State is immutable

In case you are facing any challenges with these React interview questions, please comment on your problems in the section below.

React Interview Questions

45. What are the advantages of Redux?

Advantages of Redux are listed below:

  • Predictability of outcome – Since there is always one source of truth, i.e. the store, there is no confusion about how to sync the current state with actions and other parts of the application.
  • Maintainability – The code becomes easier to maintain with a predictable outcome and strict structure.
  • Server-side rendering – You just need to pass the store created on the server, to the client side. This is very useful for initial render and provides a better user experience as it optimizes the application performance.
  • Developer tools – From actions to state changes, developers can track everything going on in the application in real time.
  • Community and ecosystem – Redux has a huge community behind it which makes it even more captivating to use. A large community of talented individuals contribute to the betterment of the library and develop various applications with it.
  • Ease of testing – Redux’s code is mostly functions which are small, pure and isolated. This makes the code testable and independent.
  • Organization – Redux is precise about how code should be organized, this makes the code more consistent and easier when a team works with it.
46. Interpolation in ReactJS?

Interpolation in ReactJS is the process of dynamically generating content by combining text strings and expressions (variables, functions, etc.) in a React component. This is typically done using the curly braces {} syntax.

Here's an example of how interpolation can be used in a React component:

function MyComponent(props) {
  const name = "John Doe";
  return (
    <div>
      <p>Hello, {name}!</p>
      <p>Your age is: {props.age}</p>
    </div>
  );
}


Here, the text string "Hello, " is combined with the name variable using interpolation. Similarly, the props.age expression is combined with the text string "Your age is: " using interpolation.

Interpolation is a powerful feature of ReactJS that allows you to generate dynamic content based on the state or props of the component. It can be used in a variety of scenarios, such as generating dynamic HTML markup, creating conditional styles, or formatting data for display.

47. Observable in ReactJs?

Observables are a powerful concept in reactive programming and can be used in ReactJS to handle asynchronous events and data streams. An observable is essentially a function that returns a stream of values over time. Observables are used in combination with reactive operators, which can be used to transform, filter, and combine these streams of values.

One popular library for working with observables in ReactJS is RxJS. RxJS provides a set of reactive operators that can be used to create, manipulate, and combine observables. Here's an example of how RxJS can be used to create and subscribe to an observable in a React component:


import { Observable } from 'rxjs'; function MyComponent() { useEffect(() => { const observable = new Observable((observer) => { // Perform some asynchronous operation const result = fetchData(); // Emit the result to the observer observer.next(result); observer.complete(); }); const subscription = observable.subscribe((result) => { // Handle the result console.log(result); }); return () => { subscription.unsubscribe(); }; }, []); return ( <div> <p>My Component</p> </div> ); }

Here, an observable is created using the Observable class from RxJS. The observable performs some asynchronous operation, such as fetching data from an API, and emits the result to the observer using observer.next(result).

A subscription is then created using the subscribe method, which takes a function that is called each time a new value is emitted by the observable. Finally, the subscription is unsubscribed when the component is unmounted to prevent memory leaks.

Observables can be a powerful tool for handling asynchronous events and data streams in ReactJS. They can be used to handle complex scenarios such as real-time data updates, event-driven user interfaces, and more. However, they can also be complex and may require a steep learning curve for beginners.

48. React Hooks?

Hooks were added to React in version 16.8. 

Hooks allow function components to have access to state and other React features. Because of this, class components are generally no longer needed. Although Hooks generally replace class components, there are no plans to remove classes from React. 

 Hooks allow us to "hook" into React features such as state and lifecycle methods.

49. Hook Rules?

There are 3 rules for hooks: 

  •  Hooks can only be called inside React function components. 
  • Hooks can only be called at the top level of a component. 
  • Hooks cannot be conditional 

 Note: Hooks will not work in React class components.

50. Various React Hook ?

      1.      useState 
2.     useEffect 
3.     useContext 
4.     useRef 
5.     useReducer 
6.     useCallback 
7.     useMemo 
8.    CustomHook

51 useState?

The React useState Hook allows us to track state in a function component. State generally refers to data or properties that need to be tracking in an application.We initialize our state by calling useState in our function component. 

useState accepts an initial state and returns two values: The current state. A function that updates the state. 

import { useState } from "react";
import ReactDOM from "react-dom/client";
 
function Car() {
  const [car, setCar] = useState({
    brand: "Ford",
    model: "Mustang",
    year: "1964",
    color: "red"
  });
 
  return (
    <>
      <h1>My {car.brand}</h1>
      <p>
        It is a {car.color} {car.model} from {car.year}.
      </p>
    </>
  )
}
 
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Car />);

 

52 useEffect?

The useEffect Hook allows you to perform side effects in your components. 

Some examples of side effects are: fetching data, directly updating the DOM, and timers. useEffect accepts two arguments. The second argument is optional. 

useEffect(<function>, <dependency>) 

useEffect runs on every render. That means that when the count changes, a render happens, which then triggers another effect. This is not what we want. There are several ways to control when side effects run. We should always include the second parameter which accepts an array. We can optionally pass dependencies to useEffect in this array. 

1. No dependency passed:

useEffect(() => {
  //Runs on every render
});

2. An empty array:

useEffect(() => {
  //Runs only on the first render
}, []);

3. Props or state values:

useEffect(() => {
  //Runs on the first render
  //And any time any dependency value changes
}, [prop, state]);

So, to fix this issue, let's only run this effect on the initial render.

Example:

Here is an example of a useEffect Hook that is dependent on a variable. If the count variable updates, the effect will run again:

import { useState, useEffect } from "react";
import ReactDOM from "react-dom/client";
 
function Counter() {
  const [count, setCount] = useState(0);
  const [calculation, setCalculation] = useState(0);
 
  useEffect(() => {
    setCalculation(() => count * 2);
  }, [count]); // <- add the count variable here
 
  return (
    <>
      <p>Count: {count}</p>
      <button onClick={() => setCount((c) => c + 1)}>+</button>
      <p>Calculation: {calculation}</p>
    </>
  );
}
 
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Counter />);

53. useContext Hook?

React Context 

React Context is a way to manage state globally. It can be used together with the useState Hook to share state between deeply nested components more easily than with useState alone. 

The Problem 

State should be held by the highest parent component in the stack that requires access to the state. To illustrate, we have many nested components. The component at the top and bottom of the stack need access to the state. To do this without Context, we will need to pass the state as "props" through each nested component. This is called "prop drilling".

The Solution

The solution is to create context.

Create Context

To create context, you must Import createContext and initialize it:

import { useState, createContext } from "react";
import ReactDOM from "react-dom/client";
 
const UserContext = createContext()

Next we'll use the Context Provider to wrap the tree of components that need the state Context.

Context Provider

Wrap child components in the Context Provider and supply the state value.

function Component1() {
  const [user, setUser] = useState("Jesse Hall");
 
  return (
    <UserContext.Provider value={user}>
      <h1>{`Hello ${user}!`}</h1>
      <Component2 user={user} />
    </UserContext.Provider>
  );
}

Now, all components in this tree will have access to the user Context.

Use the useContext Hook

In order to use the Context in a child component, we need to access it using the useContext Hook.

First, include the useContext in the import statement:

Then you can access the user Context in all components:

import { useState, createContext, useContext } from "react";

function Component5() {
  const user = useContext(UserContext);
 
  return (
    <>
      <h1>Component 5</h1>
      <h2>{`Hello ${user} again!`}</h2>
    </>
  );
}

54. useRef Hook?

The useRef Hook allows you to persist values between renders. 

 It can be used to store a mutable value that does not cause a re-render when updated. 

 It can be used to access a DOM element directly. 

 Does Not Cause Re-renders

If we tried to count how many times our application renders using the useState Hook, we would be caught in an infinite loop since this Hook itself causes a re-render. 

 To avoid this, we can use the useRef Hook. 

Example:

Use useRef to track application renders.

import { useState, useEffect, useRef } from "react";
import ReactDOM from "react-dom/client";
 
function App() {
  const [inputValue, setInputValue] = useState("");
  const count = useRef(0);
 
  useEffect(() => {
    count.current = count.current + 1;
  });
 
  return (
    <>
      <input
        type="text"
        value={inputValue}
        onChange={(e) => setInputValue(e.target.value)}
      />
      <h1>Render Count: {count.current}</h1>
    </>
  );
}
 
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);

 useRef() only returns one item. It returns an Object called current. 

When we initialize useRef we set the initial value: useRef(0). 

It's like doing this: const count = {current: 0}. We can access the count by using count.current. 

Run this on your computer and try typing in the input to see the application render count increase. 

Accessing DOM Elements 

In general, we want to let React handle all DOM manipulation. But there are some instances where useRef can be used without causing issues. 

 In React, we can add a ref attribute to an element to access it directly in the DOM. 

Example:

Use useRef to focus the input:

useEffect(() => {

import { useRef } from "react";
import ReactDOM from "react-dom/client";
function App() {
  const inputElement = useRef();
 
  const focusInput = () => {
    inputElement.current.focus();
  };
  return (
    <>
      <input type="text" ref={inputElement} />
      <button onClick={focusInput}>Focus Input</button>
    </>
  );
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);

Tracking State Changes 

The useRef Hook can also be used to keep track of previous state values. This is because we are able to persist useRef values between renders. 

Example:

Use useRef to keep track of previous state values:

import { useState, useEffect, useRef } from "react";
import ReactDOM from "react-dom/client";
 
function App() {
  const [inputValue, setInputValue] = useState("");
  const previousInputValue = useRef("");
 
  useEffect(() => {
    previousInputValue.current = inputValue;
  }, [inputValue]);
 
  return (
    <>
      <input
        type="text"
        value={inputValue}
        onChange={(e) => setInputValue(e.target.value)}
      />
      <h2>Current Value: {inputValue}</h2>
      <h2>Previous Value: {previousInputValue.current}</h2>
    </>
  );
}
 
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);

This time we use a combination of useState, useEffect, and useRef to keep track of the previous state. In the useEffect, we are updating the useRef current value each time the inputValue is updated by entering text into the input field.

55. useReducer Hook?

The useReducer Hook is similar to the useState Hook. It allows for custom state logic. If you find yourself keeping track of multiple pieces of state that rely on complex logic, useReducer may be useful. 

 Syntax 

The useReducer Hook accepts two arguments. useReducer(<reducer>, <initialstate>) The reducer function contains your custom state logic and the initialStatecan be a simple value but generally will contain an object. The useReducer Hook returns the current stateand a dispatchmethod. Here is an example of useReducer in a counter app: 

Example:

import { useReducer } from "react";
import ReactDOM from "react-dom/client";
 
const initialTodos = [
  {
    id: 1,
    title: "Todo 1",
    complete: false,
  },
  {
    id: 2,
    title: "Todo 2",
    complete: false,
  },
];
 
const reducer = (state, action) => {
  switch (action.type) {
    case "COMPLETE":
      return state.map((todo) => {
        if (todo.id === action.id) {
          return { ...todo, complete: !todo.complete };
        } else {
          return todo;
        }
      });
    default:
      return state;
  }
};
 
function Todos() {
  const [todos, dispatch] = useReducer(reducer, initialTodos);
 
  const handleComplete = (todo) => {
    dispatch({ type: "COMPLETE", id: todo.id });
  };
 
  return (
    <>
      {todos.map((todo) => (
        <div key={todo.id}>
          <label>
            <input
              type="checkbox"
              checked={todo.complete}
              onChange={() => handleComplete(todo)}
            />
            {todo.title}
          </label>
        </div>
      ))}
    </>
  );
}
 
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Todos />);

 This is just the logic to keep track of the todo complete status. All of the logic to add, delete, and complete a todo could be contained within a single useReducer Hook by adding more actions.

56. UseCallback in ReactJS?

In ReactJS, useCallback is a hook that is used to optimize performance by memoizing a function. When a function is memoized using useCallback, the function is only re-created when its dependencies change. This can help to avoid unnecessary re-renders in the application.

The syntax for useCallback is as follows:

const memoizedCallback = useCallback(
  () => {
    // Function logic goes here
  },
  [dependencies]
);

Here, memoizedCallback is a memoized function that will only be re-created when one of the dependencies changes. The dependencies parameter is an array of values that the function depends on. If any of these values change, the function will be re-created.

The primary use case for useCallback is when a function is passed as a prop to a child component. If the function is not memoized using useCallback, the child component will be re-rendered every time the parent component is re-rendered, even if the function has not changed. Memoizing the function using useCallback can help to avoid unnecessary re-renders.

Here's an example of how useCallback can be used in a parent component:

function ParentComponent() {
  const [count, setCount] = useState(0);
  const handleClick = useCallback(() => {
    setCount(count + 1);
  }, [count]);
  return (
    <div>
      <p>Count: {count}</p>
      <ChildComponent handleClick={handleClick} />
    </div>
  );
}

Here, the handleClick function is memoized using useCallback. This ensures that the function is only re-created when the count state changes. The memoized function is then passed as a prop to the ChildComponent.

Overall, useCallback is a useful hook for optimizing performance in ReactJS by memoizing functions that are used as props in child components. It helps to avoid unnecessary re-renders and improve the overall performance of the application.

57. UseMemo in ReactJS?

In ReactJS, useMemo is a hook that is used to optimize performance by memoizing a computed value. When a value is memoized using useMemo, the value is only re-computed when its dependencies change. This can help to avoid unnecessary re-renders in the application.

The syntax for useMemo is as follows:

const memoizedValue = useMemo(
  () => {
    // Computation logic goes here
  },
  [dependencies]
);

Here, memoizedValue is a memoized value that will only be re-computed when one of the dependencies changes. The dependencies parameter is an array of values that the computed value depends on. If any of these values change, the computed value will be re-computed.

The primary use case for useMemo is when a value is expensive to compute and is used multiple times in the component. Memoizing the value using useMemo can help to avoid re-computing the value every time the component is re-rendered.

Here's an example of how useMemo can be used in a component:

function MyComponent(props) {
  const [count, setCount] = useState(0);
  const expensiveValue = useMemo(() => {
    return someExpensiveComputation(props.someProp, count);
  }, [props.someProp, count]);
  return (
    <div>
      <p>Count: {count}</p>
      <p>Expensive Value: {expensiveValue}</p>
      <button onClick={() => setCount(count + 1)}>Increment Count</button>
    </div>
  );
}

Here, the expensiveValue is memoized using useMemo. This ensures that the value is only re-computed when either props.someProp or count changes. The memoized value is then used in the component multiple times without needing to recompute it.

Overall, useMemo is a useful hook for optimizing performance in ReactJS by memoizing expensive computed values. It helps to avoid unnecessary re-computations and improve the overall performance of the application.

React Router – React Interview Questions

58. What is React Router?

In ReactJS, the Route component is a part of the react-router-dom library that allows developers to define routes for different components of a single-page application. This component is used to set up a mapping between a URL path and a corresponding component that should be rendered when that path is accessed.

Here's an example of how a Route component can be defined in ReactJS:

import { Route } from 'react-router-dom';

function App() {
  return (
    <div>
      <Route exact path="/" component={Home} />
      <Route path="/about" component={About} />
      <Route path="/contact" component={Contact} />
    </div>
  );
}

In this example, the Route component is imported from the react-router-dom library and used to define three routes for different components: Home, About, and Contact.

Each Route component takes two props:

  1. path: This prop defines the URL path that should trigger the rendering of the component. For example, the path prop for the Home component is set to "/", which means that this component will be rendered when the URL path is the root URL of the application.
  2. component: This prop defines the React component that should be rendered when the corresponding URL path is accessed.

The exact prop is used to ensure that the Home component is only rendered when the URL path exactly matches the root URL. Without this prop, the Home component would be rendered for any URL path that starts with the root URL.

The Switch component can also be used to wrap the Route components, allowing only one matching route to be rendered at a time.

import { Route, Switch } from 'react-router-dom';

function App() {
  return (
    <div>
      <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/about" component={About} />
        <Route path="/contact" component={Contact} />
      </Switch>
    </div>
  );
}

This will ensure that only one of the three components is rendered, depending on the current URL path.

The Route component is a key part of building single-page applications with ReactJS, allowing developers to define different components for different URL paths and provide a seamless user experience.

59. Private Route in ReactJs?

A Private Route in ReactJS is a protected route that requires authentication before accessing it. It is used to restrict access to certain pages or components of a single-page application, such as a user profile or an admin dashboard. Private Routes are often implemented using higher-order components (HOCs) or render props that check whether a user is authenticated before rendering the protected component.

Here is an example of how to create a Private Route component using the render props approach:

import { Route, Redirect } from 'react-router-dom';

function PrivateRoute({ component: Component, isAuthenticated, ...rest }) {
  return (
    <Route {...rest} render={(props) => (
      isAuthenticated ? (
        <Component {...props} />
      ) : (
        <Redirect to={{ pathname: '/login', state: { from: props.location } }} />
      )
    )} />
  );
}

In this example, the PrivateRoute component takes three props:

  1. component: This is the protected component that should be rendered if the user is authenticated.
  2. isAuthenticated: This prop is used to check whether the user is authenticated. If this prop is true, the protected component will be rendered; otherwise, the user will be redirected to the login page.
  3. rest: This prop contains any additional props that should be passed to the Route component.

The render prop is used to conditionally render the protected component or redirect the user to the login page. If the user is authenticated, the Component prop is rendered with any additional props passed in the rest prop. If the user is not authenticated, the Redirect component is rendered to redirect the user to the login page, along with the current URL path.

To use the PrivateRoute component, you can simply wrap the protected component with the PrivateRoute component and pass in the isAuthenticated prop, like this:

function App() {
  const isAuthenticated = true;
  return (
    <div>
      <PrivateRoute path="/dashboard" component={Dashboard} isAuthenticated={isAuthenticated} />
      <Route path="/login" component={Login} />
    </div>
  );
}

In this example, the Dashboard component is wrapped with the PrivateRoute component, which requires authentication before accessing the component. The isAuthenticated prop is set to true for demonstration purposes, but in a real application, this prop would be determined by the authentication status of the user.


60. How is React Router different from conventional routing?

Conventional Routing vs React Routing

Topic

Conventional Routing

React Routing

PAGES INVOLVED

Each view corresponds to a new file

Only single HTML page is involved

URL CHANGES

A HTTP request is sent to a server and corresponding HTML page is received

Only the History attribute is changed

FEEL

User actually navigates across different pages for each view

User is duped thinking he is navigating across different pages

 61. What is a transpiler and Compiler? 

It is a tool that is used to convert source code into another source code that is of the same level. That is why it is also known as a source-to-source compiler. Both the codes are equivalent in nature, considering the fact that one works with the specific version of the browser and one doesn’t. 

It is also good to note that a compiler is totally different from a transpiler as the transpiler converts source code into another source code at the same abstraction level, whereas the compiler converts code into a lower level code generally. Like in Java, the source code is converted to byte Code which is lower level and not equivalent.

62. What is Babel?

Babel is a widely used tool in ReactJS development. ReactJS is based on modern JavaScript syntax, including ECMAScript 6 (ES6) and newer versions. However, not all browsers support the latest JavaScript syntax, so developers use Babel to transpile the modern syntax into a version that can be run in older browsers.

Babel is typically used in ReactJS development for the following purposes:

  1. Transpiling JSX syntax: JSX is a syntax extension for JavaScript that allows developers to write HTML-like syntax in JavaScript. Babel has built-in support for transpiling JSX syntax into standard JavaScript code.
  2. Transpiling modern JavaScript syntax: ReactJS relies heavily on modern JavaScript syntax, such as arrow functions, template literals, and destructuring. Babel can transpile these features into equivalent code that can be run in older browsers.
  3. Optimizing code: Babel can optimize the code generated by ReactJS to improve performance. For example, Babel can remove unused code, apply inline caching, and perform other optimizations.
  4. Configuring presets and plugins: Babel provides presets and plugins that can be used to configure the transpilation process. This allows developers to add support for additional features or customize the transformation process to meet specific needs.

Overall, Babel is an essential tool in ReactJS development, as it allows developers to write modern JavaScript code while maintaining backward compatibility with older browsers.

63. What is Create React App?

Create React App is a command-line interface tool that helps developers create a new ReactJS project quickly and easily, without having to configure build tools such as Webpack and Babel manually. It is maintained by Facebook and provides a pre-configured environment with everything needed to start building a modern single-page React application.

Create React App generates a basic project structure with all the necessary files and folders to start building a React application. It also includes a development server that supports hot reloading, which means that any changes made to the code are immediately reflected in the browser without the need to refresh the page.

Create React App provides a set of default configurations for Babel, Webpack, and ESLint, which can be further customized according to the specific needs of the project. It also includes a build script that generates a production-ready version of the application, with optimizations such as minification and code splitting.

To create a new project with Create React App, you need to have Node.js and NPM (or Yarn) installed on your system. You can then use the following command to create a new React project:

npx create-react-app my-app

Here, my-app is the name of the project, which will be created in a new folder with the same name. Once the project is created, you can use the following commands to start the development server and build the production version of the application:

npm start     // Starts the development server
npm run build // Builds the production version of the application

Create React App is a popular tool for getting started quickly with ReactJS, especially for beginners who are just starting to learn the framework. It abstracts away the complexity of setting up a modern React project, allowing developers to focus on building great user interfaces.

64. NPM vs NPX ?

NPM and NPX are both command-line tools used in the Node.js ecosystem, but they serve different purposes.

NPM (Node Package Manager) is a package manager for Node.js that allows you to install, manage, and share packages (i.e., code libraries) written in JavaScript. It is primarily used for installing and managing dependencies for a specific project. NPM maintains a registry of over one million packages that can be installed with a single command. NPM is typically used to manage dependencies in a project and to install global command-line tools.

On the other hand, NPX is a package runner that is included with NPM starting from version 5.2.0. It allows you to execute packages without having to install them globally. NPX looks for a package in your local project's node_modules folder or in the global NPM cache, and runs it directly. This means you can run a command from a package without installing it first. This is particularly useful for running tools like Babel, Webpack, or Create React App, which are often used as one-time command-line tools.

To summarize, NPM is used to manage packages and their dependencies, while NPX is used to run packages without having to install them globally.

65. What is Webpack in React?

Webpack is a popular module bundler used in the development of ReactJS applications. It is a tool that helps developers manage and optimize the various dependencies and assets used in their applications. Here are some of the uses of Webpack in ReactJS:

  1. Bundling: Webpack bundles all the modules and assets used in the application into a single file or a set of files. This reduces the number of HTTP requests required to load the application and makes it faster to load.
  2. Code splitting: Webpack allows developers to split the application into multiple chunks that can be loaded on demand. This improves the initial loading time of the application and reduces the size of the initial bundle.
  3. Loaders: Webpack allows developers to use loaders to preprocess files before they are added to the bundle. This includes transpiling JavaScript using Babel, processing CSS and SCSS files, and optimizing images.
  4. Plugins: Webpack has a rich set of plugins that can be used to perform additional optimizations and customizations. This includes minifying JavaScript, extracting CSS into separate files, and adding environment variables.
  5. Development server: Webpack provides a development server that can be used to serve the application during development. It supports features like hot module replacement and live reloading, which can speed up the development process.
  6. Configuration: Webpack is highly configurable and can be customized to meet the specific needs of the application. This includes configuring the entry point, output file, and various optimizations.

In summary, Webpack is a powerful tool that helps ReactJS developers manage and optimize their application's dependencies and assets. It provides features like bundling, code splitting, loaders, plugins, a development server, and configuration, which make the development process more efficient and productive.

Reactjs-security-best-practices

Aglowiditsolutions Webpack

https://www.toptal.com/react/webpack-react-tutorial-pt-1

66. How Webpack work in React?

React and Webpack work together to build efficient and scalable applications. Here's a high-level overview of how React and Webpack work together:

  1. React components are written in JavaScript, which is then transpiled by Babel to ensure compatibility with different browser environments.
  2. Webpack is a module bundler that is responsible for taking all the various modules, assets, and dependencies used in the application and bundling them into a single, optimized package that can be served to the browser.
  3. Webpack starts by reading a configuration file, usually named webpack.config.js, which specifies how the application should be built. This configuration file specifies the entry point of the application, the output directory and file name, and any loaders and plugins that should be used.
  4. Loaders are used to preprocess files before they are added to the bundle. For example, Babel loader is used to transpile modern JavaScript code, while CSS loader is used to process CSS files.
  5. Plugins are used to perform additional optimizations and customizations. For example, the HtmlWebpackPlugin plugin is used to generate an HTML file that references the generated bundle, while the UglifyJsPlugin is used to minify the JavaScript code.
  6. Once Webpack has bundled all the modules and assets, it outputs a single file or a set of files that can be served to the browser. These files include the bundled JavaScript code, CSS, and other assets like images and fonts.
  7. The bundled files can then be served to the browser using a web server, like Apache or Nginx. Alternatively, a development server like Webpack's dev-server can be used during development to serve the application and provide features like hot module replacement and live reloading.

Overall, React and Webpack work together to provide a powerful and efficient development experience for building modern web applications. React components are written in JavaScript, transpiled by Babel, and bundled by Webpack, resulting in optimized and scalable applications that can be served to different browser environments.

67. What is Prop Drilling?

In a traditional React application, data is often shared between components using props. Manually sharing this data can be hectic, especially when shared between multiple nested components. Also, sharing data between two child components can be cumbersome. 

Prop drilling is a situation where data is passed from one component through multiple interdependent components until you get to the component where the data is needed.

68. Error boundaries in ReactJS?

Error boundaries in ReactJS are a feature that allows developers to catch and handle errors that occur during the rendering of a component tree. By using error boundaries, you can prevent the entire application from crashing due to an unhandled error in a single component.

To create an error boundary in ReactJS, you need to define a component that implements the componentDidCatch method. This method is called whenever an error occurs during the rendering of the child components. Within this method, you can log the error or display a fallback UI to the user.

Here's an example of how an error boundary can be defined in ReactJS:

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  componentDidCatch(error, info) {
    // Log the error
    console.error(error);
    // Display a fallback UI
    this.setState({ hasError: true });
  }

  render() {
    if (this.state.hasError) {
      return <p>Something went wrong.</p>;
    }
    return this.props.children;
  }
}

In this example, ErrorBoundary is a component that defines the componentDidCatch method. Whenever an error occurs during the rendering of the child components, this method is called with the error and additional information about the error.

Within the componentDidCatch method, you can log the error using console.error or display a fallback UI to the user by setting the hasError state to true. The fallback UI can be any React component, such as an error message or a reload button.

To use the error boundary, you can wrap any component tree that you want to handle errors with the ErrorBoundary component. For example:

function MyComponent() {
  return (
    <ErrorBoundary>
      <div>
        {/* Some code that may throw an error */}
      </div>
    </ErrorBoundary>
  );
}

Here, MyComponent is wrapped with ErrorBoundary, which will catch and handle any errors that occur during the rendering of the child components.

Error boundaries are a powerful feature of ReactJS that can help prevent application crashes due to unhandled errors. By logging errors and displaying fallback UIs, you can provide a better user experience and make your application more robust.

69. What is the purpose of using super constructor with props argument in ReactJS?

Props are used to pass data from parent components to child components.  These props can be updated only by the parent component. It is read-only for child components.  We might require props inside the child component constructor with this keyword.  Super() function calls the constructor of the parent class. Using super constructor with props arguments basically allows accessing this.props in a Constructor function.

Let us create a React project and then we will create a UI to showcase the above purpose. Users will be able to see the application of the super constructor with props argument. 

70. What is the difference between ShadowDOM and VirtualDOM?

ShadowDOM

  • An API allowing developers to attach a “hidden” DOM to an element for encapsulation purposes
  • Encapsulate logic and presentation inside an element, protecting it from effects from the rest of the page
  • Browsers Implements It

VirtualDOM

  • An in-memory representation of the DOM
  • Abstract the real DOM away, allowing for better performance and a more declarative style of coding
  • JavaScript libraries, such as React and Vue

71. Why we should not update state directly?

To make React work like this, developers made React similar to functional programming. The rule of thumb of functional programming is immutability.

How does the unidirectional flow works:

  • States are a data store which contains the data of a component.
  • The view of a component renders based on the state.
  • When the view needs to change something on the screen, that value should be supplied from the store.
  • To make this happen, React provides setState() function which takes in an object of new states and does a compare and merge(similar to object.assign()) over the previous state and adds the new state to the state data store.
  • Whenever the data in the state store changes, react will trigger an re-render with the new state which the view consumes and shows it on the screen.
  • This cycle will continue throughout the component's lifetime.

If you see the above steps, it clearly shows a lot of things are happening behind when you change the state. So, when you mutate the state directly and call setState() with an empty object. The previous state will be polluted with your mutation. Due to which, the shallow compare and merge of two states will be disturbed or won't happen, because you'll have only one state now. This will disrupt all the React's Lifecycle Methods. As a result, your app will behave abnormal or even crash.

72. What is the second argument that can optionally be passed to setState and what is its purpose?

The second argument that can optionally be passed to setState is a callback function which gets called immediately after the setState is completed and the components get re-rendered. 

If you want your program to update the value of a state using setState and then perform certain actions on the updated value of state then you must specify those actions in a function which should be the second argument of the setState. If we would not do so then those actions will be performed on the previous value of state because of asynchronous nature of setState.


import React, { Component } from 'react';

class App extends Component {
constructor(props) {
super(props);
this.state = {
name: "GFG",
};
}

updateName = (value) => {
console.log("Previous name: "+this.state.name)
this.setState({ name: value}, ()=>{
// Passing it as a second parameter to setState
console.log("Current name: "+this.state.name)
});
};

render() {
const {name} = this.state;
return (
<div>
<p>Welcome To GFG</p>

<input
type="text"
value={name}
onChange={e => this.updateName(e.target.value)}
/>
</div>
);
}
}

export default App;


Explanation: On changing the value of the input field from “GFG” to “GeeksForGeeks” the console window first prints the previous value than the current value of the input field. The current value matches with the value inside the input field this happens because we have declared console.log(“Current name: “+this.state.name) function inside setState due to which console.log function gets updated value of input field.

No comments:

Post a Comment