React JS Interview Questions and Answers

Last updated 4th.Dec.2023

50+ React js interview Questions and answers both for freshers & Experienced of up to 3 years

React interview Questions

About The Author

Sai Ram Soma Having 12+ years of IT experience in React JS  & Native, JavaScript, Typescript. Working in a startup from day one. Accustomed to learning and keeping up with the current trend. Experience in developing feature rich web applications using React JS. Experience in developing mobile applications in Android, React Native.

React JS Interview questions and answers

Contents

React Masters

Interview Questions

Questions No: 1 to 10

React Masters

Interview Questions

Questions No: 11 to 20

React Masters

Interview Questions

Questions No: 21 to 30

React Masters

Interview Questions

Questions No: 31 to 40

React Masters

Interview Questions

Questions No: 41 to 50

React Masters

Interview Questions

Questions No: 51 to 62

1. What is React?

React is a front-end JavaScript library that mainly follows the component-based approach for building user interface (UI) components for a single page application. 

It is also used for handling the view layer in both mobile and web apps. Moreover, react plays a crucial role in developing interactive mobile and web UIs. 

It was created and developed by Jordan Walke; it was deployed first on the Facebook newsfeed in 2011.

React JS Interview Questions

2. Why is Reacts used?

The following reasons make one use React for building User Interfaces (UI), and they are:

  • Easy to learn nature
  • Simplicity
  • High scalability
  • Increase performance

3. How does React work?

Below is the sequence of steps which gives an idea about how does react work

  • Firstly the react runs the diffing algorithm to identify the changes that are made in the virtual DOM.
  • The next step is reconciliation, this is used to update the DOM as per the new features.
  • Now, the virtual DOM, which is lightweight in nature and is detached from the specific implementation of the browser.
  • Followingly the ReactElements which are present in virtual DOM are used to build basic nodes.
  • Finally, if the ReactComponent changes the state; the diffing algorithm runs faster and identifies the changes. After identification, it automatically updates the DOM with the change difference.

4. What are the features of ReactJS?

The features of React JS are as follows:

React improves SEO performance :

React boosts the performance of the SEO to higher levels as a search engine faces the problem while reading JavaScript of high-loaded applications.

React acts as a standard for mobile app development:

It provides a transition process as an ideal solution for both mobile and web applications for building rich user interfaces.

React makes the process of writing components easier:

Using React along with JSX will make you write components and code efficiently and clearly.

React increases efficiency:

React boosts the efficiency of components by reusing them. This is the reason why it is considered an ideal feature of React. It is considered the most reusable system component.

React ensures stable code:

It ensures the stability of the code of an application by making use of downward data flow.

5. What are some of the important features of React?

React is a JavaScript library for building user interfaces. It is often used for building single-page applications and mobile applications, as it allows developers to create reusable UI components.

 

6.What is React and why is it used?

React has multiple features that are used for unique purposes. The important ones are as mentioned below:

  • React makes use of a single-direction data flow model.
  • It deals with complete server-side data processing and handling.
  • React uses Virtual DOM that has many advantages of its own.

7. How is React different from other JavaScript libraries?

React is a JavaScript library for building user interfaces. It was developed by Facebook, and is often used for building single-page applications and mobile applications.

One of the main differences between React and other JavaScript libraries is that it uses a virtual DOM (Document Object Model) to optimize updates to the actual DOM. 

When a component’s state changes in a React application, the virtual DOM creates a new virtual tree of React elements. 

This virtual tree is then compared to the previous virtual tree, and the virtual DOM determines the minimum number of actual DOM mutations required to reflect the changes in the virtual tree. 

This helps to improve the performance of a React application by reducing the number of costly DOM operations.

Another key difference between React and other JavaScript libraries is that it uses a declarative programming style. 

This means that instead of telling the library how to update the DOM when a component’s state changes, you simply declare what the UI should look like based on a given state. 

React then takes care of updating the DOM to match the desired state.

In summary, React is a JavaScript library that is optimized for building user interfaces, and it uses a virtual DOM and a declarative programming style to improve performance and make it easier to build complex UI components.

8. What is the meaning of JSX?

JSX is the abbreviation of JavaScript XML. It is a file that is used in React to bring out the essence of JavaScript to React and use it for its advantages. It even includes bringing out HTML and the easy syntax of JavaScript. This ensures that the resulting HTML file will have high readability, thereby relatively increasing the performance of the application. 

9. Can browsers read a JSX file?

No, browsers cannot read JSX files directly. It can only read the objects provided by JavaScript. Now, to make a browser read a JSX file, it has to be transformed to a JavaScript object using JSX transformers, and only then it can be fed into the browser for further use in the pipeline.

10. Why is React widely used today?

React provides users with an ample number of advantages when building an application. Some of them are as follows:

  • With React, UI testing becomes very easy.
  • React can integrate with Angular and other frameworks easily.
  • The high readability index ensures easy understanding.
  • React can be used for both client-side and server-side requirements.
  • It boosts application performance and overall efficiency.

or want to continue reading React JS Interview Questions

11. What is the virtual DOM?

DOM stands for Document Object Model. The DOM represents an HTML document with a logical tree structure. Each branch of the tree ends in a node, and each node contains objects.

React JS Interview Questions Answers

React keeps a lightweight representation of the real DOM in the memory, and that is known as the virtual DOM. When the state of an object changes, the virtual DOM changes only that object in the real DOM, rather than updating all the objects. 

The following are some of the most frequently asked react interview questions.

React JS Interview Questions Answers

12. Are there any disadvantages to using React?

There are some limitations when using React as mentioned below:

  • Writing code is complicated as it uses JSX and inline template formatting.
  • Beginners might find it tough to cope with its syntaxes and methods.
  • The library contains a huge repository of information, which might be overwhelming.
  • React is a simple library and not a complete framework hence calls for dependencies.

13. How is the React JS framework different as compared to others?

Basically, ReactJS is a limited library that builds UI parts, it is essentially not quite the same as a considerable measure of other JavaScript structures. 

One common example is AngularJS approaches building an app simply by expanding HTML markup and infusing different developments such as controllers at runtime. 

Therefore, AngularJS is exceptionally obstinate about the more noteworthy engineering of your application.

14. What are the life Cycles of ReactJS?

  1. Initialization
  2. State/Property Updates
  3. Destruction

15. What is the use of refs?

Entry Refs provide a way to access DOM nodes or React elements created in the render method. They should be avoided in most cases, however, they can be useful when we need direct access to the DOM element or an instance of a component.

There are a few good use cases for refs:

  • Managing focus, text selection, or media playback.
  • Triggering imperative animations.
  • Integrating with third-party DOM libraries.

Refs are created using React.createRef() and attached to React elements via the ref attribute. Refs are commonly assigned to an instance property when a component is constructed so they can be referenced throughout the component.

class MyComponent extends React.Component {

  constructor(props) {

    super(props);

    this.myRef = React.createRef();  }

  render() {

    return <div ref={this.myRef} />;  }

}

16. What are props in React?

Props are inputs to a React component. They are single values or objects containing a set of values that are passed to React Components on creation using a naming convention similar to HTML-tag attributes. i.e, 

They are data passed down from a parent component to a child component.

The primary purpose of props in React is to provide the following component functionality:

  1. Pass custom data to your React component.
  2. Trigger state changes.
  3. Use via this.props.reactProp inside component render() method.

For example, let us create an element with reactProp property,

<Element reactProp = “1” />

This reactProp (or whatever you came up with) the name then becomes a property attached to React’s native props object which originally already exists on all components created using React library.

props.reactProp;

17. What are React Hooks?

Hooks are a new addition to React 16.8. They let you use state and other React features without writing a class.

With Hooks, you can extract stateful logic from a component so it can be tested independently and reused. Hooks allow you to reuse stateful logic without changing your component hierarchy. 

This makes it easy to share Hooks among many components or with the community.

18. What are the major features of ReactJS?

The major features of ReactJS are as follows,

  • It uses VirtualDOM instead of RealDOM considering that RealDOM manipulations are expensive.
  • Supports server-side rendering
  • Follows Unidirectional data flow or data binding

19. What is the meaning of the component-based architecture of React?

In React, components are foundations used to build user interfaces for applications. With the component-based system in place, all of the individual entities become completely reusable and independent of each other. 

This means that rendering the application is easy and not dependent on the other components of the UI.

20. How does rendering work in React?

Rendering is an important aspect of React as every single component must be rendered. This is done using the render() function. Once the function is called, it returns an element that represents a DOM component.

It is also possible to render more than one HTML element at a time by enclosing the HTML tags and passing them through the render function.

Learn  React Js  from our  Expert  Trainer 

21. What are states in React?

Rendering is an important aspect of React as every single component must be rendered. This is done using the render() function. Once the function is called, it returns an element that represents a DOM component.

It is also possible to render more than one HTML element at a time by enclosing the HTML tags and passing them through the render function.

States form to be one of the vital aspects of React. It is considered as a source of data or objects that control aspects such as component behavior and rendering. In React, states are used to easily create dynamic and interactive components. 

22. How is React JS different from Angular JS?

The first difference between both of them is their code dependency. ReactJS depends less on the code whereas AngularJS needs a lot of coding to be done. The packaging on React is quite strong as compared to AngularJS. 

Another difference is React is equipped with Virtual Dom while Angular has a Regular DOM. ReactJS is all about the components whereas AngularJS focus mainly on the Models, View as well as on Controllers. 

AngularJS was developed by Google while ReactJS is the outcome of Facebook. These are some of the common differences between the two.

23. What is Redux?

It is one of the most in-demand libraries for front-end development in today’s growing world. It is defined as the predictable state container mainly designed for JavaScript apps and also it is used for managing the entire state of an application. 

Redux is very small in size and has no dependencies. It builds applications that are easy to deploy in different environments and easy to test. Redux is very small in size and has no dependencies.

24. What is the Use of Redux thunk?

Redux thunk acts as middleware which allows an individual to write action creators that return functions instead of actions. This is also used as a delay function in order to delay the dispatch of action if a certain condition is met. The two store methods getState() and dispatch() are provided as parameters to the inner function.

In order to activate Redux thunk, we must first use applyMiddleware() method as shown below:

import{ createStore, applyMiddleware } from ‘redux’;

import thunk from ‘redux-thunk’;

import rootReducer from ‘./reducers/index’;

//Note: this API requires redux@>=3.1.0

const store= createStore(

     rootReducer,

25. What do you know about Flux?

Basically, Flux is a basic illustration that is helpful in maintaining the unidirectional data stream.  It is meant to control constructed data’s unique fragments to make them interface with that data without creating issues. 

Flux configuration is insipid; it’s not specific to React applications, nor is it required to collect a React application.  Flux is basically a straightforward idea, however, you have to exhibit a profound comprehension of its usage.

26. What is the current stable version of ReactJS?

******Version: 16.12.0 

******Release on: Nov 14, 2019

27. What is the use of an arrow function in React?

An arrow function is used to write an expression in React. It allows users to manually bind components easily. The functionality of arrow functions can be very useful when you are working with higher-order functions particularly.

Consider the following example:

//The usual way

render() {

return(

<MyInput onChange={this.handleChange.bind(this) } />

);

}

//Making use of the arrow function

render() {

return(

<MyInput onChange={ (e) => this.handleOnChange(e) } />

);

}

28. What is the difference between the ES6 and ES5 standards?

This is one of the most frequently asked react interview questions.

These are the few instances where ES6 syntax has changed from ES5 syntax:

  • Components and Function

React JS Interview Questions Answers

  • exports vs export

React JS Interview Questions  Answers

  • require vs import

React JS Interview Questions Answers

29. How do you create a React app?

These are the steps for creating a React app:

  • Install NodeJS on the computer because we need npm to install the React library. Npm is the node package manager that contains many JavaScript libraries, including React.

React JS Interview Questions Answers

  • Install the create-react-app package using the command prompt or terminal.

React JS Interview Questions Answers

  • Install a text editor of your choice, like VS Code or Sublime Text.

React JS Interview QuestionsAnswers

We have put together a set of Node.js interview questions in case you would like to explore them.Please note, This is one of the most frequently asked react interview questions.

30. What is an event in React?

An event is an action that a user or system may trigger, such as pressing a key, a mouse click, etc.

  • React events are named using camelCase, rather than lowercase in HTML.
  • With JSX, you pass a function as the event handler, rather than a string in HTML.
<Button onPress={lightItUp} />

Learn  React Js  from our  Expert  Trainer 

31. What is a higher-order component in React?

Higher-order components (HOCs) are a widely used technique in React for applying concepts that involve the component reusability logic. They are not a native part of the React API and allow users to easily reuse the code and bootstrap abstraction.

HOCs are also used to allow simple sharing of behaviors across all of the components in React, adding more advances to the efficiency and functioning of the application.

32. What is the meaning of create-react-app in React?

The create-react app in React is a simple command-line interface (CLI) that is used in the creation of React applications, which have no build configuration.

All tools are pre-configured when using the CLI, and this allows users to focus on the code more than on dependencies to develop the application.

The following syntax is used to start a simple project in React:

Create-react-app my-app

33. What are some of the advantages of using create-react-app in React?

Making use of create-react-app is advantageous in the following way:

  • Support for JSX, ES6, and flow statements
  • Already built and ready auto-prefixed CSS
  • Fast interactive testing components
  • Live development servers that help in debugging
  • Scripts to handle JSS, CSS, and other files

34. What are the three phases of a component life cycle in React?

The following are the three phases of a component life cycle:

  • Initial rendering: This is the phase that involves the beginning of the journey of the component to the DOM.
  • Update: Here, the component can be updated and rendered again if required after it gets added to the DOM.
  • Unmounting: The final phase involves the destruction of the component and its eventual removal from the DOM.

35. How is routing in React different from conventional routing?

Differences between the conventional routing and the routing in React can be shown using the following aspects:

  • Pages: Each view is considered as a new file in conventional routing while it is considered as a single HTML entity in React.
  • Navigation: In conventional routing, users have to move across web pages for viewing. In React, the views are not refreshed as objects are re-issued to create new views.

36. How do the parent and child components exchange information?

This task is generally performed with the help of functions. Actually, there are several functions that are provided to both parent and child components. 

They simply make use of them through props. Their communication should be accurate and reliable. The need for the same can be there anytime and therefore functions are considered for this task. 

They always make sure that information can be exchanged easily and in an efficient manner among the parent and child components.

37. What is a State in React and How is it used?

In React, State is an object that represents how the component renders and behaves. States are the sources of data and allow you to create dynamic and interactive components. 

They are accessed using this.state(). For changing a value in the state object, call it using this.setState() method.

38. Can AJAX be used with React?

Yes, any AJAX library, such as Axios and jQuery AJAX, can be used with React easily. One important thing is to maintain the states of the components, and here too, the props are passed from the parents to the child components.

Child components still cannot send back props to parents, and this factor greatly increases rendering efficiency when dynamic data is considered.

Learn  React Js  from our  Expert  Trainer 

39. Why is a router required in React?

A router is very much necessary in React as it is used to manage multiple routes whenever a user types in a URL. If the route is present in the router for that corresponding URL, then the user is taken to the particular route.

To do this, the router library needs to be added in React. It can be done using the following syntax:

<switch>

<route exact path=’/’ component={Home}/>

<route path=’/posts/:id’ component={Newpost}/>

<route path=’/posts’   component={Post}/>

</switch>

Learn  React Js  from our  Expert  Trainer 

41. How to embed two components in One component?

import React from ‘react’;

class App extends React.Component{

    render(){

        return(

            <div>

            <Header/>

            <Content/>

            </div>

        );

    }

}

class Header extends React.Component{

    render(){

        return(

    <div>

            <h1> Header</h1>

            </div>

        )

    }

}

class Content extends React.Component{

    render(){

        return(

            <h2>Content</h2>

            <p>The Content Text!!!</p>

            </div>

        )

    }

}

export default App;

42. How do you tell React to build in Production mode and what will that do?

Ordinarily, you’d utilize Webpack’s DefinePlugin strategy to set NODE_ENV to production. This will strip out things like prototype approval and additional notices. 

Over that, it’s likewise a smart thought to minify your code in light of the fact that React utilizes Uglify’s dead-code end to strip out advancement just code and remarks, which will radically diminish the measure of your package. 

43.How do you implement a forwardRef in a React component?

A forwardRef is a way to pass a reference to a DOM element from a parent component to a child component. It’s useful when you want to access the DOM element directly from the child component, for example to focus on an input element or to measure its size.

To implement a forwardRef in a React component, you can use the React.forwardRef function to create a new component that wraps your existing component and passes the ref through to it. Here’s an example of how to do this:

import React from ‘react’;
return (
   <div ref={ref}>
   {props.name}
   </div>
  );
  });
export default MyComponent;

In this example, the MyComponent component accepts a ref prop and passes it through to the div element.

To use this component, you can pass a ref to it from a parent component like this:

import React, { useRef } from ‘react’;

import MyComponent from ‘./MyComponent’;

const ParentComponent = () => {

const ref = useRef(null);

return <MyComponent ref={ref} name=“John” />;

};

Now, you can use the ref object in the parent component to access the DOM element in the child component. For example, you can focus on the div element like this:

ref.current.focus();

Note that forwardRef is only necessary if you want to pass a ref to a DOM element through a component that is not a DOM element itself. If you are passing a ref to a DOM element directly, you don’t need to use forwardRef.

44.How do you implement a custom hook in a React application?

To implement a custom hook in a React application, you can follow these steps:
  1. Create a JavaScript function that starts with the word use and performs the specific logic that you want the hook to handle.

  2. Inside the hook function, you can declare state variables and perform side effects using React’s useState and useEffect hooks. You can also call other hooks within your custom hook to reuse logic.

  3. To use your custom hook, import it into the component where you want to use it and call it inside the component’s function body.

Here’s an example of a custom hook that manages a piece of state called count:

import { useState, useEffect } from ‘react’;

function useCounter(initialCount) {
const [count, setCount] = useState(initialCount);

useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`;
});

return [count, setCount];
}

To use this hook in a component, you can import it and call it inside the component’s function body:

import React from ‘react’;
import { useCounter } from ‘./useCounter’;

function MyComponent() {
const [count, setCount] = useCounter(0);

return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}

Custom hooks can be a powerful way to abstract logic out of your components and share it across your application. They can help you write reusable and more maintainable code.

 

45.Can you explain the purpose of the React.useEffect() hook?

In React, the useEffect hook allows you to perform side effects in function components. It is a way to handle lifecycle events and to perform tasks that don’t directly relate to rendering the component, such as fetching data from a server or updating the DOM.

useEffect is called after every render, including the first render. This means that the function passed to useEffect will be called after the component has been rendered to the screen. 

It is a good place to perform tasks that need to happen after the component has been updated, such as fetching data or updating the DOM.

You can think of useEffect as a combination of the componentDidMount, componentDidUpdate, and componentWillUnmount lifecycle methods from class-based components.

Here is an example of using useEffect to fetch data from a server and update the component’s state when the data is received:

import { useEffect, useState } from ‘react’;

function MyComponent() {
const [data, setData] = useState(null);

useEffect(() => {
fetch(‘https://my-api.com/data’)
.then(response => response.json())
.then(data => setData(data));
}, []);

return <div>{data}</div>;
}

In this example, the useEffect hook is called after the component is rendered, and it triggers a data fetch. 

The fetched data is then stored in the component’s state using the setData function, which causes the component to re-render with the new data.

You can also specify a list of dependencies as the second argument to useEffect. If any of the dependencies change, the effect will be re-run. 

This is useful for limiting the number of times the effect is run, to avoid unnecessary work. For example:

import { useEffect, useState } from ‘react’;

function MyComponent(props) {
const [data, setData] = useState(null);

useEffect(() => {
fetch(`https://my-api.com/data?id=${props.id}`)
.then(response => response.json())
.then(data => setData(data));
}, [props.id]);

return <div>{data}</div>;
}

In this example, the effect will only be run when the props.id value changes. This means that if the id prop is the same as the previous render, the effect will not be run again, which can improve performance.

Learn  React Js  from our  Expert  Trainer 

46.Can you explain the purpose of the React.useContext() hook?

Yes, the useContext hook in React is a way to access the value of a context object from a function component.

Context is a feature in React that allows you to share values across components without the need to pass props down through multiple levels of the component tree. 

This can be useful for sharing values that are likely to be needed by many components in an application, such as the current authenticated user, theme, or language preference.

To use the useContext hook, you first need to create a context object using the React.createContext function. This function takes an optional default value as an argument and returns an object with a Provider component and a Consumer component. 

The Provider component is used to provide the context value to its descendants, and the Consumer component is used to retrieve the value from the context.

Here is an example of how you might create a context object and use it in a function component:

const MyContext = React.createContext();

function MyComponent() {
const contextValue = React.useContext(MyContext);
return <div>{contextValue}</div>;
}

function App() {
return (
<MyContext.Provider value=”Hello World”>
<MyComponent />
</MyContext.Provider>
);
}

In this example, the MyComponent function component uses the useContext hook to retrieve the value of the MyContext context object, which is “Hello World”. The MyContext.Provider component, which is a descendant of MyComponent, provides the value of the context object to MyComponent.

47.How do you implement code splitting in a React application?

Code splitting is a technique that allows you to split your application’s code into smaller chunks that can be loaded on demand, rather than all at once. 

This can help improve the performance of your application by reducing the initial load time and allowing you to only load the code that is actually needed at a given moment.

There are a few ways to implement code splitting in a React application. One way is to use the React.lazy function and the Suspense component, which are part of the React API.

Here is an example of how you might use React.lazy and Suspense to code split a component:

import React, { Suspense, lazy } from ‘react’;

const MyComponent = lazy(() => import(‘./MyComponent’));

function App() {
return (
<Suspense fallback={<div>Loading…</div>}>
<MyComponent />
</Suspense>
);
}

In this example, the MyComponent component is imported as a lazy component using the lazy function. 

The Suspense component is used to wrap the lazy component and provides a fallback element to render while the lazy component is being loaded.

Another way to implement code splitting in a React application is to use a tool like React Router or Webpack to automatically split your code into chunks based on the routes or modules in your application.

48.Can you explain the purpose of the React.useMemo() hook?

Yes, the useMemo hook in React is a way to optimize the performance of a function component by caching the result of a expensive computation and only re-computing it if one of the inputs to the computation has changed.

The useMemo hook takes a function and a list of dependencies as arguments, and returns the result of the function. If the dependencies have not changed since the last time the function was called, the result is returned from the cache. 

If the dependencies have changed, the function is called again and the result is cached for future use.

Here is an example of how you might use the useMemo hook to optimize the performance of a function component:

import { useMemo } from ‘react’;

function MyComponent({ data }) {
const processedData = useMemo(() => {
// Do expensive computation on data here
return processedData;
}, [data]);

return (
<div>
{processedData.map(item => (
<div key={item.id}>{item.name}</div>
))}
</div>
);
}

In this example, the processedData variable is computed using the useMemo hook and is only re-computed if the data prop changes. 

This can help improve the performance of the component by avoiding unnecessary re-computations if the data prop has not changed.

49.How do you implement reconciliation in a React application?

Reconciliation is the process that React uses to update the virtual DOM (VDOM) and the actual DOM in response to changes in the component’s state or props.

When a component’s state or props change, React compares the VDOM representation of the component with the previous VDOM representation to determine what changes need to be made to the actual DOM. This process is called reconciliation.

React uses a heuristic approach to reconciliation, which means that it tries to minimize the number of DOM updates by making smart decisions about which elements in the actual DOM need to be updated.

50. Give me two most significant drawbacks of React

React is a popular and powerful JavaScript library for building user interfaces, but like any tool, it has its limitations. Here are two significant drawbacks of React:

  1. Steep learning curve: React is a large and complex library, and there is a lot to learn to use it effectively. This can be intimidating for developers who are new to the library, or who are coming from a different UI framework.

  2. Poor performance with large lists: React is designed to efficiently update the UI as the state of an application changes. However, if you have a very large list of items and need to update it frequently, the performance of React can suffer. This is because React needs to re-render the entire list whenever an update occurs, which can be computationally expensive. To work around this issue, you can use techniques such as virtualization, which allows you to only render a subset of the items in the list at a given time.

 
 
 

51. What is dispatcher? 

In the context of a JavaScript application, a dispatcher is a central hub that coordinates actions and updates between different parts of the app. It is often used in conjunction with a system for managing application state

52.What is meant by callback function? What is its purpose?

A callback function is a function that is passed as an argument to another function, and is executed after the outer function has completed. Callback functions are often used in JavaScript to perform an action after some asynchronous operation has completed.

For example, consider the following code that uses the setTimeout function to log a message after a delay:

setTimeout(function() {
console.log(‘Hello, world!’);
}, 1000);

In this code, the anonymous function function() { console.log('Hello, world!'); } is passed as a callback to the setTimeout function. The setTimeout function will execute the callback after a delay of 1000 milliseconds (1 second).

The purpose of callback functions is to allow you to specify an action to be taken at a later time, without blocking the execution of the rest of your code. 

This can be useful in situations where you need to perform an action after some asynchronous operation has completed, such as making an HTTP request or reading from a file.

Callbacks are also used extensively in event-driven programming, where you may want to specify a function to be called when a certain event occurs. For example, you might use a callback to handle a button click event or a form submission event.

53.Explain the Presentational segment?

The presentational segment in a URL refers to the part of the URL that specifies how the content should be displayed to the user. It includes information about the layout and formatting of the content, such as the language, character set, and style sheets to be used.

For example, consider the following URL:

https://www.example.com/page.html?language=en&theme=light

In this URL, the presentational segment includes the query string parameters “language=en” and “theme=light”. These parameters specify that the content should be displayed in English and with a light theme, respectively.

The presentational segment is optional in a URL and is typically used to customize the way that content is displayed to the user. It is important to note that the presentational segment does not affect the content itself, but only how it is presented to the user.

54. Name two types of React component

Two types of react Components are:

  • Function component
  • Class component

55. What are fragments?

In the context of React, a fragment is a way to group a list of children without adding extra nodes to the DOM. Fragments allow you to return multiple elements from a component’s render method without wrapping them in an additional element.

56. Why is it necessary to start component names with a capital letter?

In React, it is a convention to start component names with a capital letter. This is because components are intended to be reusable pieces of code that represent a part of the user interface, 

and in JavaScript, a convention for naming class constructors (which are used to create components in React) is to start the name with a capital letter.

57. How to apply validation on props in React?

There are several ways to apply validation on props in a React component. One way is to use the prop-types library, which is a part of the React ecosystem and provides a way to define the types of props that a component expects to receive.

58. What is create-react-app?

create-react-app is a command-line tool that helps you create a new React project with a preconfigured development environment. 

It is a quick and easy way to get started with a new React project, especially if you are new to React or don’t want to spend a lot of time setting up a build configuration.

59. Is it possible for a web browser to read JSX directly?

No, web browsers cannot read JSX directly. JSX is a syntax extension for JavaScript, and it needs to be transformed into regular JavaScript code before a web browser can understand and execute it.

60. How to create refs?

In React, a ref is a way to access the properties of a DOM element. You can create a ref by using the React.createRef() method and attaching it to a DOM element.

61. What are Forward Refs

Forward refs are a way to pass a ref through a component to one of its children. This can be useful when you need to access the properties of a child component from the parent component.

62. What is the use of Refs?

The Ref in React is used in the following cases:

  • It is used to return a reference to the element.
  • It is used when we need DOM measurements such as managing focus, text selection, or media playback.
  • It is used in triggering imperative animations.
  • It is used when integrating with third-party DOM libraries.
  • It can also use as in callbacks.
 

Learn  React Js  from our  Expert  Trainer 

Enroll for the Live Demo Class

*By filling the form you are giving us the consent to receive emails from us regarding all the updates.