react js

react interview questions, interview question react js, top react interview question, react interview question and answers, react interview question, react interview question for senior developer


💡 What is DOM or real DOM?

DOM stands for “Document Object Model”. It represents the entire UI of the web application as a tree data structure. In simple terms, it is a structural representation of the web application’s HTML parts & elements.


💡 Why Real DOM is slow?

The issue with Real Dom is that it is costly for browsers. To reflect changes in the user interface, the browser must seek, check, and parse the number of nodes. It is easy for small changes but as the number of changes in UI increases, efficiency decreases, making the browser slower.


💡 What is the Virtual DOM?

The virtual DOM (VDOM) is a programming concept where an ideal, or “virtual”, representation of a UI is kept in memory and synced with the “real” DOM by a library such as ReactDOM. This process is called reconciliation.

when you render a JSX element, every virtual DOM object gets modified. After the virtual DOM has been modified, React compares it to a virtual DOM snapshot that was taken right before the update and stored in memory. By comparing the new virtual DOM with a pre-update version, React figures out exactly which virtual DOM objects have changed. This process is called “diffing.”


💡 What is DOM Diffing?

Whenever there is a change in the state of the UI elements, a new virtual DOM is created. Then the new virtual DOM and the previous virtual DOM are compared with each other. This comparison is called DOM diffing.


💡 Where is virtual DOM stored?

React has a virtual DOM which is a copy of the actual DOM and is kept in the browser Memory in the form of a javascript object.


💡 Is the Shadow DOM the same as the Virtual DOM?

No, they’re not the same. The Shadow DOM is a browser feature that allows you to scope variables and CSS in web components. The virtual DOM is a notion that is implemented using JavaScript libraries on top of browser APIs.


💡 How to optimize the DOM size in React?

  • Use a “windowing” library like react-window to minimize the number of DOM nodes created if you are rendering many repeated elements on the page.
  • Minimize unnecessary re-renders using shouldComponentUpdate, PureComponent, or React.memo.
  • Skip effects only until certain dependencies have changed if you are using the Effect hook to improve runtime performance. You can tell React to skip applying an effect if certain values haven’t changed between re-renders. To do so, pass an array as an optional second argument to useEffect.


💡 Explain Virtual DOM? How does it solve the problem of rendering that is in real DOM?

Updating a real DOM does not involve just updating the DOM but, it also entails a number of other procedures. When we update any node or element in a real dom, the following happens. If we update the real DOM ten times, each of the steps below will be repeated ten times. This is why Real DOM updates are slow.

document.getElementById('elementId').innerHTML = "Updated Value"
  • The browser has to parse the HTML and then It removes the child element of that elementId.
  • Updates the DOM with the “New Value”.
  • Re-calculate the CSS for the parent and child. – It uses complex algorithms that affect performance.
  • Update the layout i.e. each element’s exact coordinates on the screen
  • Traversing the render tree and painting it on the browser display

Virtual DOM is a representation of real DOM that is stored in memory. It’s a lightweight JavaScript object that’s a replica of the Real DOM.
ReactJS generates the entire Virtual DOM from scratch whenever the setState() method is called. Because creating a full tree takes so little time, it has little impact on performance. ReactJS keeps two virtual DOMs in memory at any given time, one with the updated state Virtual DOM and the other with the prior state Virtual DOM.

ReactJS uses the diff algorithm to find the minimum number of steps to update the Real DOM. Once it has these steps, it executes all the steps in one event loop. Once all the steps are executed, React will repaint the Real DOM. This means during the event loop, there is exactly one time when the Real DOM is being painted. Thus all the layout processes will run only on time for updating the real DOM.

Read here more –
https://medium.com/@happymishra66/virtual-dom-in-reactjs-43a3fdb1d130


💡 Which Algorithm, react js used to traverse the dom tree?

Breadth First Search – ReactJS traverses the tree using BFS. So when any parent element gets updated, react js re-renders all its children by default. This is the reason to use BFS for tree traversal.
If the state of a component has changed, then ReactJS re-renders all the child components even if child components are not modified. To prevent the unwanted re-render of the child components we can use shouldComponentUpdate() component life cycle method. This will further help in boosting performance.


💡 What is the meaning of mount and unmount?

A React component mounts when it renders to the DOM for the first time. If it’s already mounted, a component can be rendered again if it needs to change its appearance or content.

React supports one unmounting lifecycle method, componentWillUnmount, which will be called right before a component is removed from the DOM.


💡 What are the life cycle phases of a component?

There are three categories of lifecycle methods: mounting, updating, and unmounting.

  • A component “mounts” when it renders for the first time. This is when mounting lifecycle methods get called.
  • When a component instance renders for the first time, it does not update. A component updates every time it renders starts with the second render.
  • When a component is removed from the DOM, it enters its unmounting period. This could happen if the DOM is rerendered without the component, or if the user navigates to a different website or closes their web browser.


💡 What is the role of the constructor in a class component?

constructor(props)

The below content is as per React’s official document.

The constructor for a React component is called before it is mounted. When implementing the constructor for a React.Component subclass, you should call super(props) before any other statement. Otherwise, this.props will be undefined in the constructor, which can lead to bugs. Typically, React constructors are only used for two purposes:

  • Initializing local state by assigning an object to this.state.
  • Binding event handler methods to an instance.
constructor(props) {
  super(props);
  // Don't call this.setState() here!
  this.state = { counter: 0 };
  this.handleClick = this.handleClick.bind(this);
}

constructor(props) {
 super(props);
 // Don't do this! you can use this.props.color directly instead
 this.state = { color: props.color };
}


💻 Three points need to take care of while using the constructor –

  • You should not call setState() in the constructor(). Instead, if your component needs to use a local state, assign the initial state to this.state directly in the constructor.
  • Constructor is the only place where you should assign this.state directly. In all other methods, you need to use this.setState() instead.
  • If you don’t initialize the state and you don’t bind methods, you don’t need to implement a constructor for your React component.


💡 Is Super call required in a class component?

class AComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { subject: 'math' };
  }
}

Yes, React class components should call super(props) in their constructors in order to properly set up their this.props object.

Top React JS Interview Questions and Answers


💡 Explain Class component life cycle methods?

Read here the official document for all life cycle methods –
https://reactjs.org/docs/react-component.html#constructor

Life Cycle diagram –
https://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/

constructor()

//Follow above question

componentDidMount()

componentDidMount() is invoked immediately after a component is mounted (inserted into the tree). If you need to load data from a remote endpoint, this is a good place to instantiate the network request. This method is a good place to set up any subscriptions. If you do that, don’t forget to unsubscribe in componentWillUnmount().

componentDidUpdate()

componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render.

componentWillUnmount()

componentWillUnmount() is invoked immediately before a component is unmounted and destroyed. Perform any necessary cleanup in this method, such as invalidating timers, canceling network requests, or cleaning up any subscriptions that were created in componentDidMount().


💡 Can we call setState() in componentDidUpdate?

You may call setState() immediately in componentDidUpdate() but note that it must be wrapped in a condition like in the example below, or you’ll cause an infinite loop.

componentDidUpdate(prevProps) {
  // (don't forget to compare props
  if (this.props.userID !== prevProps.userID) {
	this.setState({name: 'Js Mount'});
	// Can also hit a request if any need.
    this.fetchData(this.props.userID);
  }
}


💡 What if we call setState() from within componentWillUnmount?

You should not call setState() in componentWillUnmount() because the component will never be re-rendered. Once a component instance is unmounted, it will never be mounted again.


💡 Explain shouldComponentUpdate() method and its use case?

shouldComponentUpdate(nextProps, nextState)

If you know your component doesn’t need to update in some instances, you can return false from shouldComponentUpdate to bypass the entire rendering process, including running render() on this component and below.
The default behavior is to re-render on every state change, and in the vast majority of cases, you should rely on the default behavior. This method only exists as a performance optimization.

In most circumstances, instead of writing shouldComponentUpdate() by hand, you can inherit it from React.PureComponent. It is equivalent to implementing shouldComponentUpdate() with a shallow comparison of current and previous props and states.

Top React JS Interview Questions and Answers


💡 What is the purpose of getDerivedStateFromProps?

static getDerivedStateFromProps is a new React lifecycle method as of React 16.4 designed to replace componentWillReceiveProps.
getDerivedStateFromProps exists for only one purpose. It enables a component to update its internal state as a result of changes in props. Since it is a static method, you cannot access “this” inside method neither you can access any other class method.
The reason getDerivedStateFromProps is static is to discourage any side effects during the render phase.

 static getDerivedStateFromProps(props, state) {
//do stuff here
  } 


💡 When we use getSnapshotBeforeUpdate() life cycle method?

After the DOM is updated, the getSnapshotBeforeUpdate lifecycle method stores the previous state data. getSnapshotBeforeUpdate() is called right after the render method.
This lifecycle mechanism is unlikely to be used frequently. However, it’s useful when you need to get information from the DOM (and maybe change it) just after an update.
Any value returned by this lifecycle method will be passed as a third parameter to componentDidUpdate().

 getSnapshotBeforeUpdate(prevProps, prevState) {
    // Are we adding new items to the list?
    // Capture the scroll position so we can adjust scroll later.
    if (prevProps.list.length < this.props.list.length) {
      const list = this.listRef.current;
      return list.scrollHeight - list.scrollTop;
    }
    return null;
  }
  
    componentDidUpdate(prevProps, prevState, snapshot) {
    // If we have a snapshot value, we've just added new items.
    // Adjust scroll so these new items don't push the old ones out of view.
    // (snapshot here is the value returned from getSnapshotBeforeUpdate)
    if (snapshot !== null) {
      const list = this.listRef.current;
      list.scrollTop = list.scrollHeight - snapshot;
    }
  }


💡 What are Error handling lifecycle methods?

Errors are thrown when things go wrong in your code. When a descendant component throws an error, the following methods are called (i.e., a component below them).

  • static getDerivedStateFromError()
  • componentDidCatch()


💡 What are Error boundaries?

In React 16, Error boundaries were introduced as a means to catch and handle JavaScript failures that occur in our component’s tree, log those errors, and display a fallback UI instead of the component tree that crashed. As a result, error boundaries only detect problems in lifecycle methods, rendering methods, and Hooks like useEffect. Error boundaries, according to the React documentation, do not handle failures in:

  • Event handlers
  • Asynchronous code (e.g., setTimeout or requestAnimationFrame callbacks)
  • Server-side rendering
  • Errors are thrown in the error boundary itself (rather than its children)

A class component becomes an error boundary if it defines either (or both) of the lifecycle methods static getDerivedStateFromError() or componentDidCatch().

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

  static getDerivedStateFromError(error) {
    // Update state so that next render will show the fallback UI.
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    console.log(errorInfo);
    logErrorToMyService(error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return <h1>Something went wrong.</h1>;
    }

    return this.props.children; 
  }
}

static getDerivedStateFromError(error)

Whenever an error is thrown in a descendant component, this method is called first, and the error is thrown and passed as an argument.
getDerivedStateFromError() is called during the “render” phase, so side-effects are not permitted, that’s why this method is static. For those use cases, use componentDidCatch() instead.

componentDidCatch(error, errorInfo)

This lifecycle is invoked after an error has been thrown by a descendant component. It receives two parameters: error and info.


💻 How to Use:

   <ErrorBoundary>
          <OrderComponent/>
   </ErrorBoundary>

You can read this article also for life cycle methods:
https://blog.logrocket.com/react-lifecycle-methods-tutorial-examples/

Top React JS Interview Questions and Answers


💡 Explain setState() method?

setState() enqueues changes to the component state and instructs React to re-render this component and its descendants with the changed state. This is the primary method you use to update the user interface in response to event handlers and server responses.
setState() does not always update the component immediately; instead, it may defer the update until later for better performance.

setState(updater, [callback])

updater

A function with the signature: (state, props) => stateChange.
state is the current, up-to-date component state, and the function returns the updated state.

callback

An optional callback function that is guaranteed to run after the state has been updated.

this.setState((state, props) => {
  return {count: state.count + props.step};
});

Another way - you can pass an object instead of an updater function >

this.setState({count: 2})


💡 What is forceUpdate() method?

component.forceUpdate(callback)

By default, when your component’s state or props change, your component will re-render. If your render() method depends on some other data, you can tell React that the component needs re-rendering by calling forceUpdate().


💡 How to update nested state properties in ReactJS?

We can do this in two ways –

  • First, We can build a dummy object and use it to conduct operations (such as updating properties), then replace the component’s state with the changed object.
  • Second, We can pass the old nested object using the spread operator and then override the particular properties of the nested object.
// Nested object
  state = {
    employeeId: '3142',
    address: {
      city: 'Mumbai',
      state: 'MH'
    }
  };
  // First way >

  handleUpdate = () => {
    // Creating a dummy object using spread operator
    var address = { ...this.state.address }
  
    // Updating the city
    address.city = 'Delhi';
    this.setState({ address })
  }
   
   // Second way >

   handleUpdate = () => {
    // Overriding the city property of address object
    this.setState({ address: { ...this.state.address, city: "Delhi" } })
  }

react interview questions, interview question react js, top react interview question, react interview question and answers, react interview question, react interview question for a senior developer