Join Regular Classroom : Visit ClassroomTech

ReactJS Interview Questions – Beginner Level | Codewindow.in

1. What is Node.js?

React is an open-source frontend JavaScript library which is used for building user interfaces especially for single page applications. It is used for handling 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.

2. 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.

3. How to create components in React?

There are two possible ways to create a component.

Function Components: This is the simplest way to create a component. Those are pure JavaScript functions that accept props object as first parameter and return React elements:

function Greeting({ message }) {
  return <h1>{`Hello, ${message}`}</h1>

}

/*
Class Components: You can also use ES6 class to define a component. The above function component can be written as:
*/

class Greeting extends React.Component {
  render() {
    return <h1>{`Hello, ${this.props.message}`}</h1>
  }
}

4. What is state in React?

State of a component is an object that holds some information that may change over the lifetime of the component. We should always try to make our state as simple as possible and minimize the number of stateful components.

Let’s create a user component with message state:

class User extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      message: 'Welcome to React world'
    }
  }

  render() {
    return (
      <div>
        <h1>{this.state.message}</h1>
      </div>
    )
  }
}

/*
State is similar to props, but it is private and fully controlled by the component. 
i.e, It is not accessible to any other component til the owner component decides to pass it.
*/

5. What are props in React?

Props are inputs to components. They are single values or objects containing a set of values that are passed to components on creation using a naming convention similar to HTML-tag attributes. They are data passed down from a parent component to a child component.

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

Pass custom data to your component.

Trigger state changes.

Use via this.props.reactProp inside component’s render() method.

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

<Element reactProp={‘1’} />

This reactProp (or whatever you came up with) 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

C QA

Mostly Asked

DS QA

Mostly Asked

DBMS QA

Mostly Asked

ML QA

Mostly Asked

6. How to pass a parameter to an event handler or callback?

You can use an arrow function to wrap around an event handler and pass parameters:

<button onClick={() => this.handleClick(id)} />
// This is an equivalent to calling .bind:
<button onClick={this.handleClick.bind(this, id)} />
// Apart from these two approaches, you can also pass arguments to a function which is defined as arrow function
<button onClick={this.handleClick(id)} />
handleClick = (id) => () => {
    console.log("Hello, your ticket number is", id)
};

7. How Virtual DOM works?

The Virtual DOM works in three simple steps.

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

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

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

8. What are the lifecycle methods of React?

Before React 16.3

componentWillMount: Executed before rendering and is used for App level configuration in your root component.

componentDidMount: Executed after first rendering and here all AJAX requests, DOM or state updates, and set up event listeners should occur.

componentWillReceiveProps: Executed when particular prop updates to trigger state transitions.

shouldComponentUpdate: Determines if the component will be updated or not. By default it returns true. If you are sure that the component doesn’t need to render after state or props are updated, you can return false value. It is a great place to improve performance as it allows you to prevent a re-render if component receives new prop.

componentWillUpdate: Executed before re-rendering the component when there are props & state changes confirmed by shouldComponentUpdate() which returns true.

componentDidUpdate: Mostly it is used to update the DOM in response to prop or state changes.

componentWillUnmount: It will be used to cancel any outgoing network requests, or remove all event listeners associated with the component.

React 16.3+
getDerivedStateFromProps: Invoked right before calling render() and is invoked on every render. This exists for rare use cases where you need derived state. Worth reading if you need derived state.
componentDidMount: Executed after first rendering and where all AJAX requests, DOM or state updates, and set up event listeners should occur.
shouldComponentUpdate: Determines if the component will be updated or not. By default it returns true. If you are sure that the component doesn’t need to render after state or props are updated, you can return false value. It is a great place to improve performance as it allows you to prevent a re-render if component receives new prop.
getSnapshotBeforeUpdate: Executed right before rendered output is committed to the DOM. Any value returned by this will be passed into componentDidUpdate(). This is useful to capture information from the DOM i.e. scroll position.
componentDidUpdate: Mostly it is used to update the DOM in response to prop or state changes. This will not fire if shouldComponentUpdate() returns false.
componentWillUnmount It will be used to cancel any outgoing network requests, or remove all event listeners associated with the component.

9. What is 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)

10. How to set 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 })

}

11. Why React uses 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>
}

12. Why fragments are better than container divs?

Below are the list of reasons:

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.

Some CSS mechanisms like Flexbox and CSS Grid have a special parent-child relationships, and adding divs in the middle makes it hard to keep the desired layout.

The DOM Inspector is less cluttered.

13. What are portals in React?

Portal is a recommended way to render children into a DOM node that exists outside the DOM hierarchy of the parent component.
ReactDOM.createPortal(child, container)
The first argument is any render-able React child, such as an element, string, or fragment. The second argument is a DOM element.

14. What are stateless components?

If the behaviour 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 the this keyword altogether.

15. What are stateful components?

If the behaviour of a component is dependent on the state of the component then it can be termed as stateful component. These stateful components are always class components and have a state that gets initialized in the constructor.

class App extends Component {
  constructor(props) {
    super(props)
    this.state = { count: 0 }
  }
  render() {
    // ...
  }
}

// React 16.8 Update:
// Hooks let you use state and other React features without writing classes.
// The Equivalent Functional Component

 import React, {useState} from 'react';
 const App = (props) => {
   const [count, setCount] = useState(0);
   return (
     // JSX
   )
 }

16. What is the use of react-dom package

The react-dom package provides DOM-specific methods that can be used at the top level of your app. Most of the components are not required to use this module. Some of the methods of this package are:

render()

hydrate()

unmountComponentAtNode()

findDOMNode()

createPortal()

17. Can you force a component to re-render without calling setState?

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().

component.forceUpdate(callback)

It is recommended to avoid all uses of forceUpdate() and only read from this.props and this.state in render().

Categories
Pages
Recent Posts