React interview Questions

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

What are the different phases of the component lifecycle?

- Initialization - Mounting - Updating - Unmounting

What are the different ways to style a React component?

- Inline Styling: - Using JavaScript object: - CSS Stylesheet - CSS Modules

Using useMemo( )

- It is a React hook that is used for caching CPU-Expensive functions. - Sometimes in a React app, a CPU-Expensive function gets called repeatedly due to re-renders of a component, which can lead to slow rendering.useMemo( ) hook can be used to cache such functions. By using useMemo( ), the CPU-Expensive function gets called only when it is needed.

Using React.PureComponent

- It is a base component class that checks the state and props of a component to know whether the component should be updated. - Instead of using the simple React.Component, we can use React.PureComponent to reduce the re-renders of a component unnecessarily.

What is the importance of keys?

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

What are the rules that must be followed while using React Hooks?

- React Hooks must be called only at the top level. It is not allowed to call them inside the nested functions, loops, or conditions. - It is allowed to call the Hooks only from the React Function Components

Maintaining State Colocation -

- This is a process of moving the state as close to where you need it as possible. - Sometimes in React app, we have a lot of unnecessary states inside the parent component which makes the code less readable and harder to maintain. Not to forget, having many states inside a single component leads to unnecessary re-renders for the component. - It is better to shift states which are less valuable to the parent component, to a separate component.

Name a few techniques to optimize React app performance.

- Using useMemo( ) - - Using React.PureComponent - - Maintaining State Colocation - - Lazy Loading -

What does strictmode currently helps with?

-Identifying components with unsafe lifecycle methods: -Warning about the usage of legacy string API: - Warning about the usage of findDOMNode: -Warning about the usage of legacy context API (because the API is error-prone).

main purpose of props?

-Passing custom data to the React component. -Using through this.props.reactProp inside render() method of the component. -Triggering state changes.

Reason for re-renders in React:

-Re-rendering of a component and its child components occur when props or the state of the component has been changed. -Re-rendering components that are not updated, affects the performance of an application.

Limitations of React?

-react is not a full-blown framework as it is only a library -components of React are numerous and will take time to fully grasp the benefits of all -might be difficult for beginner programmers to understand React -Coding might become complex as it will make use of inline templating and JSX

Important Features of React?

-supports server side rendering -makes use of the virtual DOM rather than real DOM(data object model) of real DOM manipulations are expensive -follows unidirectional data binding or data flow -uses reusable or composable UI components for developing the view

Advantages of React?

-use of virtual DOM to improve efficiency -gentle learning curve (if you know JS its easy to pick up) -SEO friendly -reusable components (increase pace of development) -huge ecosystem of libraries to choose from

What are Custom Hooks?

A Custom Hook is a function in Javascript whose name begins with 'use' and which calls other hooks. It is a part of React v16.8 hook update and permits you for reusing the stateful logic without any need for component hierarchy restructuring. In almost all of the cases, custom hooks are considered to be sufficient for replacing render props and HoCs (Higher-Order components) and reducing the amount of nesting required. Custom Hooks will allow you for avoiding multiple layers of abstraction or wrapper hell that might come along with Render Props and HoCs. The disadvantage of Custom Hooks is it cannot be used inside of the classes

What are keys in React?

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

What is an error boundary?

Any component which uses one of the following lifecycle methods is considered an error boundary. In what places can an error boundary detect an error? - Render phase - Inside a lifecycle method - Inside the constructor

What are the differences between functional and class components?

Before the introduction of Hooks in React, functional components were called stateless components and were behind class components on a feature basis. After the introduction of Hooks, functional components are equivalent to class components.

Explain conditional rendering in React.

Conditional rendering refers to the dynamic output of user interface markups based on a condition state. It works in the same way as JavaScript conditions. Using conditional rendering, it is possible to toggle specific application functions, API data rendering, hide or show elements, decide permission levels, authentication handling, and so on. There are different approaches for implementing conditional rendering in React. Some of them are: - Using if-else conditional logic which is suitable for smaller as well as for medium-sized applications - Using ternary operators, which takes away some amount of complication from if-else statements - Using element variables, which will enable us to write cleaner code.

What are the differences between controlled and uncontrolled components?

Controlled and uncontrolled components are just different approaches to handling input from elements in react.

Why was virtual DOM introduced?

DOM manipulation is quite slow when compared to other operations in JavaScript. The efficiency of the application gets affected when several DOM manipulations are being done. Most JavaScript frameworks update the entire DOM even when a small part of the DOM changes. To address the problem of inefficient updating, the react team introduced the concept of virtual DOM.

Initialization

During this phase, React component will prepare by setting up the default props and initial state for the upcoming tough journey.

What are error boundaries?

Error boundaries provide a way for us to catch errors that occur in the render phase.

React Props

Every React component accepts a single object argument called props (which stands for "properties"). These props can be passed to a component using HTML attributes and the component accepts these props as an argument. Note- Props are read-only. They cannot be manipulated or changed inside a component.

React State

Every component in react has a built-in state object, which contains all the property values that belong to that component.In other words, the state object controls the behaviour of a component. Any change in the property values of the state object leads to the re-rendering of the component.

How does it work?

For every DOM object, there is a corresponding virtual DOM object(copy), which has the same properties. The main difference between the real DOM object and the virtual DOM object is that any changes in the virtual DOM object will not reflect on the screen directly. Consider a virtual DOM object as a blueprint of the real DOM object. Whenever a JSX element gets rendered, every virtual DOM object gets updated. React uses two virtual DOMs to render the user interface. One of them is used to store the current state of the objects and the other to store the previous state of the objects. Whenever the virtual DOM gets updated, react compares the two virtual DOMs and gets to know about which virtual DOM objects were updated. After knowing which objects were updated, react renders only those objects inside the real DOM instead of rendering the complete real DOM. This way, with the use of virtual DOM, react solves the problem of inefficient updating. Basically virtual DOM is the blueprint of the real DOM, easier to update the virtual DOM

What are Higher Order Components?

Higher-Order Component(HOC) is a function that takes in a component and returns a new component.

What are Hooks?

Hooks are functions that let us "hook into" React state and lifecycle features from a functional component.

Controlled component:

In a controlled component, the value of the input element is controlled by React. We store the state of the input element inside the code, and by using event-based callbacks, any changes made to the input element will be reflected in the code as well.

uncontrolled component?

In an uncontrolled component, the value of the input element is handled by the DOM itself. Input elements inside uncontrolled components work just like normal HTML input form elements.

Unmounting

In this last phase of the component lifecycle, the component will be removed from the DOM or will be unmounted from the browser DOM. This phase will have the lifecycle method named componentWillUnmount.

Updating

In this phase, a component will be updated when there is a change in the state or props of a component. This phase will have lifecycle methods like componentWillUpdate, shouldComponentUpdate, render, and componentDidUpdate.

Routes

It is a newer component that has been introduced in the React v6 and an upgrade of the component.

BrowserRouter:

It is a router implementation that will make use of the HTML5 history API (pushState, popstate, and event replaceState) for keeping your UI to be in sync with the URL. It is the parent component useful in storing all other components.

Lazy Loading -

It is a technique used to reduce the load time of a React app. Lazy loading helps reduce the risk of web app performances to a minimum

Route

It is considered to be a conditionally shown component and some UI will be rendered by this whenever there is a match between its path and the current URL

How to re-render the view when the browser is resized?

It is possible to listen to the resize event in componentDidMount() and then update the width and height dimensions. It requires the removal of the event listener in the componentWillUnmount() method.

Link

It is useful in creating links to various routes and implementing navigation all over the application. It works similarly to the anchor tag in HTML.

What is JSX?

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

Mounting

Mounting refers to putting the elements into the browser DOM. Since React uses VirtualDOM, the entire browser DOM which has been currently rendered would not be refreshed. This phase includes the lifecycle methods componentWillMount and componentDidMount.

How to pass data between react components?

Parent Component to Child Component (using props)

How to pass data between sibling components using React router?

Passing data between sibling components of React is possible using React Router with the help of history.push and match.params.

Why were Hooks introduced in React?

Previously, functional components were called stateless components. Only class components were used for state management and lifecycle methods. The need to change a functional component to a class component, whenever state management or lifecycle methods were to be used, led to the development of Hooks.

What is React Hooks?

React Hooks are the built-in functions that permit developers for using the state and lifecycle methods within React components. These are newly added features made available in React 16.8 version. Each lifecycle of a component is having 3 phases which include mount, unmount, and update. Along with that, components have properties and states. Hooks will allow using these methods by developers for improving the reuse of code with higher flexibility navigating the component tree.

What is React Router?

React Router refers to the standard library used for routing in React. It permits us for building a single-page web application in React with navigation without even refreshing the page when the user navigates. It also allows to change the browser URL and will keep the user interface in sync with the URL. React Router will make use of the component structure for calling the components, using which appropriate information can be shown. Since React is a component-based framework, it's not necessary to include and use this package. Any other compatible routing library would also work with React.

Why is React seo friendly?

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

What are the lifecycle methods of React?

React lifecycle hooks will have the methods that will be automatically called at different phases in the component lifecycle and thus it provides good control over what happens at the invoked point. It provides the power to effectively control and manipulate what goes on throughout the component lifecycle. constructor() getDerivedStateFromProps() render() componentDidMount() shouldComponentUpdate() getSnapshotBeforeUpdate() componentDidUpdate() componentWillUnmount()

How does use of virtual DOM improve React's effieciency?

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

SEO meaning

Search Engine Optimization

Effects with Cleanup:

Some of the Hook effects will require the cleanup after updating of DOM is done. For example, if you want to set up an external data source subscription, it requires cleaning up the memory else there might be a problem of memory leak. It is a known fact that React will carry out the cleanup of memory when the unmounting of components happens. But the effects will run for each render() method rather than for any specific method. Thus we can say that, before execution of the effects succeeding time the React will also cleanup effects from the preceding render.

What is prop drilling in React?

Sometimes while developing React applications, there is a need to pass data from a component that is higher in the hierarchy to a component that is deeply nested. To pass data between such components, we pass props from a source component and keep passing the prop to the next component in the hierarchy till we reach the deeply nested component.

Does React Hook work with static typing?

Static typing refers to the process of code check during the time of compilation for ensuring all variables will be statically typed. React Hooks are functions that are designed to make sure about all attributes must be statically typed. For enforcing stricter static typing within our code, we can make use of the React API with custom Hooks.

Explain Strict Mode in React.

StrictMode is a tool added in version 16.3 of React to highlight potential problems in an application. It performs additional checks on the application.

shouldComponentUpdate()

The Boolean value will be returned by this method which will specify whether React should proceed further with the rendering or not. The default value for this method will be True.

Can React Hook replaces Redux?

The React Hook cannot be considered as a replacement for Redux (It is an open-source, JavaScript library useful in managing the application state) when it comes to the management of the global application state tree in large complex applications, even though the React will provide a useReducer hook that manages state transitions similar to Redux. Redux is very useful at a lower level of component hierarchy to handle the pieces of a state which are dependent on each other, instead of a declaration of multiple useState hooks.

What are props in React?

The props in React are the inputs to a component of React. They can be single-valued or objects having a set of values that will be passed to components of React during creation by using a naming convention that almost looks similar to HTML-tag attributes. We can say that props are the data passed from a parent component into a child component.

How to perform automatic redirect after login?

The react-router package will provide the component <Redirect> in React Router. Rendering of a <Redirect> component will navigate to a newer location. In the history stack, the current location will be overridden by the new location just like the server-side redirects.

What is the use of useEffect React Hooks?

The useEffect React Hook is used for performing the side effects in functional components. With the help of useEffect, you will inform React that your component requires something to be done after rendering the component or after a state change. The function you have passed(can be referred to as "effect") will be remembered by React and call afterwards the performance of DOM updates is over. Using this, we can perform various calculations such as data fetching, setting up document title, manipulating DOM directly, etc, that don't target the output value. The useEffect hook will run by default after the first render and also after each update of the component. React will guarantee that the DOM will be updated by the time when the effect has run by it. The useEffect React Hook will accept 2 arguments: useEffect(callback[, dependencies]); Where the first argument callback represents the function having the logic of side-effect and it will be immediately executed after changes were being pushed to DOM. The second argument dependencies represent an optional array of dependencies. The useEffect() will execute the callback only if there is a change in dependencies in between renderings.

What is useState() in React?

The useState() is a built-in React Hook that allows you for having state variables in functional components. It should be used when the DOM has something that is dynamically manipulating/controlling.

componentDidUpdate()

This method will be called after the component has been updated in the DOM.

componentDidMount()

This method will be called after the rendering of the component. Using this method, you can run statements that need the component to be already kept in the DOM

getDerivedStateFromProps()

This method will be called just before element(s) rendering in the DOM. It helps to set up the state object depending on the initial props. The getDerivedStateFromProps() method will have a state as an argument and it returns an object that made changes to the state. This will be the first method to be called on an updating of a component.

constructor()

This method will be called when the component is initiated before anything has been done. It helps to set up the initial state and initial values.

componentWillUnmount()

This method will be called when the component removal from the DOM is about to happen.

render()

This method will output or re-render the HTML to the DOM with new changes. The render() method is an essential method and will be called always while the remaining methods are optional and will be called only if they are defined.

getSnapshotBeforeUpdate()

This method will provide access for the props as well as for the state before the update. It is possible to check the previously present value before the update, even after the update.

Effects without Cleanup

This side effect will be used in useEffect which does not restrict the browser from screen update. It also improves the responsiveness of an application. A few common examples are network requests, Logging, manual DOM mutations, etc.

When do we need a Higher Order Component?

While developing React applications, we might develop components that are quite similar to each other with minute differences. In most cases, developing similar components might not be an issue but, while developing larger applications we need to keep our code DRY, therefore, we want an abstraction that allows us to define this logic in a single place and share it across components. HOC allows us to create that abstraction.

What is React?

front-end, open source JS library. Useful in developing user interfaces specifically for single page apps. Helpful in building complex and reusable user interface(UI) components of mobile and web applications as it follows the component-based approach.

Why do React Hooks make use of refs?

refs were only limited to class components but now it can also be accessible in function components through the useRef Hook in React. The refs are used for: - Managing focus, media playback, or text selection. - Integrating with DOM libraries by third-party. - Triggering the imperative animations.

What is seo process?

the process used to optimize a website's technical configuration, content relevance and link popularity so its pages can become easily findable, more relevant and popular towards user search queries, and as a consequence, search engines rank them better.

Explain about types of side effects in React component.

two types: with cleanup and without cleanup

Disadvantage of prop drilling?

using prop drilling is that the components that should otherwise be not aware of the data have access to the data

What is the virtual DOM?

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


संबंधित स्टडी सेट्स

Ch 6 Cash, Fraud, and Internal Control

View Set

Generally Accepted Accounting Principles

View Set

Module 2: Self-Awareness and Values Formation

View Set

Chapter 42: Organization and Financial Structure of Corporations (SmartBook Assignment)

View Set

PSI - NY Life, Accident and Health Practice Exam 17-55, Just my cards + 199+ 75 ( TEST) (LOT)

View Set

Chapter 6 History of R & R - What's That Sound?

View Set

Digital Imaging Unit 2 - Processing (Review ) RT5

View Set

Immunology: B and T-Cell Development

View Set