What is React js

React JS Interview Questions

React is a JavaScript library for building user interfaces. It is based on ES6 Script Extension. ES6 is ECMA Script 2015. React provides seamless manipulation and rendering of DOM objects.

We also consider it as a Popular JavaScript framework based on Redux Architecture. React is developed and maintained by Facebook Inc. React was first created by Jordan Walke, a software engineer working for Facebook. Facebook is using React since 2011 and Instagram since 2012.

So it is a necessary skill to have in your stack. You will be considered if you are an expert in React JS.  Here are some important React Js Interview Questions and Answers useful for Javascript Interview.

What is React?

React is an open-source front-end JavaScript library that is used for building user interfaces especially for single-page applications. It is used for handling the view layer for web and mobile apps. React was created by Jordan Walke, a software engineer working for Facebook. React was first deployed on Facebook’s News Feed in 2011 and on Instagram in 2012.  Read more about – What is React JS?

What are the major features of React?

The major features of React are:

  • It uses VirtualDOM instead of RealDOM considering that RealDOM manipulations are expensive.
  • Supports server-side rendering.
  • Follows Unidirectional data flow or data binding.
  • Uses reusable/composable UI components to develop the view.

What is JSX?

JSX is a XML-like syntax extension to ECMAScript (the acronym stands for JavaScript XML). Basically it just provides syntactic sugar for the React.createElement() function, giving us expressiveness of JavaScript along with HTML like template syntax.

In the example below the text inside the <h1> tag returns as JavaScript function to the render function.

class App extends React.Component {

  render() {

    return(

      <div>

        <h1>{'Welcome to React world!'}</h1>

      </div>

    )

  }

}

What are Pure Components?

React.PureComponent is exactly the same as React. Component except that it handles the shouldComponentUpdate() method for you. When props or state changes, PureComponent will do a shallow comparison on both props and state. A component, on the other hand, won’t compare current props and state to next out of the box. Thus, the component will re-render by default whenever shouldComponentUpdate is called.

What is the difference between state and props?

Both props and state are plain JavaScript objects. While both of them hold information that influences the output of render, they are different in their functionality with respect to the component. Props get passed to the component similar to function parameters whereas the state is managed within the component similar to variables declared within a function.

What is the use of refs?

The ref is used to return a reference to the element. They should be avoided in most cases, however, they can be useful when you need direct access to the DOM element or an instance of a component.

What is Virtual DOM?

The Virtual DOM (VDOM) is an in-memory representation of Real DOM. The representation of a UI is kept in memory and synced with the “real” DOM. It’s a step that happens between the render function being called and the displaying of elements on the screen. This entire process is called reconciliation.

What is the difference between Shadow DOM and Virtual DOM?

The Shadow DOM is a browser technology designed primarily for scoping variables and CSS in web components. The Virtual DOM is a concept implemented by libraries in JavaScript on top of browser APIs.

What is React Fiber?

Fiber is the new reconciliation engine or reimplementation of the core algorithm in React v16. The goal of React Fiber is to increase its suitability for areas like animation, layout, gestures, ability to pause, abort, or reuse work and assign priority to different types of updates; and new concurrency primitives.

What is the main goal of React Fiber?

The goal of React Fiber is to increase its suitability for areas like animation, layout, and gestures. Its headline feature is incremental rendering: the ability to split rendering work into chunks and spread it out over multiple frames.

What are the controlled components?

A component that controls the input elements within the forms on subsequent user input is called Controlled Component, i.e, every state mutation will have an associated handler function.

For example, to write all the names in uppercase letters, we use handleChange as below,

handleChange(event) {

  this.setState({value: event.target.value.toUpperCase()})

}

How to create props proxy for the HOC component?

You can add/edit props passed to the component using props proxy pattern like this:

function HOC(WrappedComponent) {

  return class Test extends Component {

    render() {

      const newProps = {

        title: 'New Header',

        footer: false,

        showFeatureX: false,

        showFeatureY: true

      }

      return <WrappedComponent {...this.props} {...newProps} />

    }

  }

}

What is the context?

Context provides a way to pass data through the component tree without having to pass props down manually at every level. For example, authenticated user, locale preference, UI theme need to be accessed in the application by many components.

const {Provider, Consumer} = React.createContext(defaultValue)

What is a child prop?

Children are a prop (this.prop.children) that allow you to pass components as data to other components, just like any other prop you use. Component tree put between component’s opening and closing tag will be passed to that component as children prop.

There are a number of methods available in the React API to work with this prop. These include React.Children.map, React.Children.forEach, React.Children.count, React.Children.only, React.Children.toArray. A simple usage of children prop looks as below,

 

const MyDiv = React.createClass({

  render: function() {

    return <div>{this.props.children}</div>

  }

})

ReactDOM.render(

  <MyDiv>

    <span>{'Hello'}</span>

    <span>{'World'}</span>

  </MyDiv>,

  node

)

What is reconciliation?

When a component’s props or state change, React decides whether an actual DOM update is necessary by comparing the newly returned element with the previously rendered one. When they are not equal, React will update the DOM. This process is called reconciliation.

How to set a state with a dynamic key name?

If you are using ES6 or the Babel transpiler to transform your JSX code then you can accomplish this with computed property names.

 

handleInputChange(event) {

  this.setState({ [event.target.id]: event.target.value })

}

 

Why does React use className over class attribute?

class is a keyword in JavaScript, and JSX is an extension of JavaScript. That’s the principal reason why React uses className instead of class. Pass a string as the className prop.

render() {

  return <span className={'menu navigation-menu'}>{'Menu'}</span>

}

Why are fragments better than container divs?

  1. Fragments are a bit faster and use less memory by not creating an extra DOM node. This only has a real benefit on very large and deep trees.
  2. Some CSS mechanisms like Flexbox and CSS Grid have special parent-child relationships, and adding divs in the middle makes it hard to keep the desired layout.
  3. The DOM Inspector is less cluttered.

 

What are stateless components?

If the behavior is independent of its state then it can be a stateless component. You can use either a function or a class for creating stateless components. But unless you need to use a lifecycle hook in your components, you should go for function components. There are a lot of benefits if you decide to use function components here; they are easy to write, understand, and test, a little faster, and you can avoid this keyword altogether.

What are the advantages of React?

  1. Increases the application’s performance with Virtual DOM.
  2. JSX makes code easy to read and write.
  3. It renders both on client and server-side (SSR).
  4. Easy to integrate with frameworks (Angular, Backbone) since it is only a view library.
  5. Easy to write unit and integration tests with tools such as Jest.

 

What are the limitations of React?

  1. React is just a view library, not a full framework.
  2. There is a learning curve for beginners who are new to web development.
  3. Integrating React into a traditional MVC framework requires some additional configuration.
  4. The code complexity increases with inline templating and JSX.
  5. Too many smaller components leading to over-engineering or boilerplate.

How are error boundaries handled in React v15?

React v15 provided very basic support for error boundaries using the unstable_handleError method. It has been renamed to componentDidCatch in React v16.

What is the purpose of the render method of react-dom?

This method is used to render a React element into the DOM in the supplied container and return a reference to the component. If the React element was previously rendered into a container, it will perform an update on it and only mutate the DOM as necessary to reflect the latest changes.

ReactDOM.render(element, container[, callback])

 

If the optional callback is provided, it will be executed after the component is rendered or updated.

How to use innerHTML to React?

The dangerouslySetInnerHTML attribute is React’s replacement for using innerHTML in the browser DOM. Just like innerHTML, it is risky to use this attribute considering cross-site scripting (XSS) attacks. You just need to pass an __html object as key and HTML text as value.

In this example MyComponent uses dangerouslySetInnerHTML attribute for setting HTML markup:

function createMarkup() {

  return { __html: 'First &middot; Second' }

}


function MyComponent() {

  return <div dangerouslySetInnerHTML={createMarkup()} />

}

How events are different in React?

Handling events in React elements has some syntactic differences:

  1. React event handlers are named using camelCase, rather than lowercase.
  2. With JSX you pass a function as the event handler, rather than a string.

What will happen if you use setState() in the constructor?

When you use setState(), then apart from assigning to the object state React also re-renders the component and all its children. You would get an error like this: Can only update a mounted or mounting component. So we What will happen if you use setState() in the constructor? What will happen if you use setState() in the constructor? need to use this.state to initialize variables inside the constructor.

How do you conditionally render components?

In some cases, you want to render different components depending on some state. JSX does not render false or undefined, so you can use conditional short-circuiting to render a given part of your component only if a certain condition is true.

const MyComponent = ({ name, address }) => (

  <div>

    <h2>{name}</h2>

    {address &&

      <p>{address}</p>

    }

  </div>

)

If you need an if-else condition then use a ternary operator.

const MyComponent = ({ name, address }) => (

  <div>

    <h2>{name}</h2>

    {address

      ? <p>{address}</p>

      : <p>{'Address is not available'}</p>

    }

  </div>

)

 

Spread the love
  • 1
    Share
Dhananjay

Dhananjay

I’m Dhananjay — a free-spirit with a passion for technologies and blogging.

View all posts by Dhananjay →

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.