ReactJS Interview Questions

ReactJS interview questions

ReactJS Interview Questions

1. What is ReactJS
React is a declarative, efficient, and flexible JavaScript library for building reusable and stateful user interfaces. It lets you compose complex UIs from small and isolated pieces of code called “components”. ReactJS is developed Facebook.

2. What are Components in ReactJS?

React components are small, reusable pieces of code that return a React element to be rendered to the page. The simplest version of React component is a plain JavaScript function that returns a React element. In other words, components are like JavaScript functions.

function Welcome(props) {
    return <h1>Hello, {props.name}</h1>;
}

class Welcome extends React.Component {
    render() {
        return <h1>Hello, {this.props.name}</h1>;
    }
}

Here, props are inputs to a React component. They are data passed down from a parent component to a child component.

Components can be broken down into distinct pieces of functionality and used within other components. Components can return other components, arrays, strings and numbers.

3. Difference between Controlled vs. Uncontrolled Components

React has two different approaches to dealing with form inputs.

An input form element whose value is controlled by React is called a controlled component. When a user enters data into a controlled component a change event handler is triggered and your code decides whether the input is valid (by re-rendering with the updated value). If you do not re-render then the form element will remain unchanged.

An uncontrolled component works like form elements do outside of React. When a user inputs data into a form field (an input box, dropdown, etc) the updated information is reflected without React needing to do anything. However, this also means that you can’t force the field to have a certain value.

In most cases you should use controlled components.

4. What is JSX?

JSX is a syntax extension to JavaScript. It is similar to a template language, but it has full power of JavaScript. JSX gets compiled to React.createElement() calls which return plain JavaScript objects called “React elements”.

const element = <h1>Hello, world!</h1>;

This tag syntax is neither a string nor HTML. It is called JSX, and it is a syntax extension to JavaScript. JSX produces React “elements”.

Basically JSX is an XML/HTML-like syntax used by React that extends ECMAScript so that XML/HTML-like text can co-exist with JavaScript/React code. The syntax is intended to be used by preprocessors (i.e., transpilers like Babel) to transform HTML-like text found in JavaScript files into standard JavaScript objects that a JavaScript engine will parse.

Using JSX script

var nav = (
      <ul id="nav"> 
             <li><a href="#">React</li>
             <li><a href="#">JavaScript<li>
       </ul>
);

And Babel will transform it into this:

var nav = React.createElement(
                  "ul",
                   { id: "nav" },
                    React.createElement(
                        "li",
                          null,
                          React.createElement(
                           "a",
                            { href: "#" }, 
                             "React"
                            )
                      ),
                   React.createElement(
                    "li",
                      null,
                      React.createElement(
                        "a",
                       { href: "#" },
                       "JavaScript"
                        )
                   )
              );

 

 5. Describe The Component Life cycle

Each component has several “life cycle methods” that you can override to run code at particular times in the process. You can use this life cycle diagram as a cheat sheet. In the list below, commonly used life cycle methods are marked as bold. The rest of them exist for relatively rare use cases.

Mounting

These methods are called in the following order when an instance of a component is being created and inserted into the DOM:

constructor()
static getDerivedStateFromProps()
render()
componentDidMount()

 

Updating

An update can be caused by changes to props or state. These methods are called in the following order when a component is being re-rendered:

static getDerivedStateFromProps()
shouldComponentUpdate()
render()
getSnapshotBeforeUpdate()
componentDidUpdate()

 

Unmounting
This method is called when a component is being removed from the DOM:

componentWillUnmount()

Error Handling

This method is called when there is an error during rendering, in a lifecycle method, or in the constructor of any child component.

componentDidCatch()

Other APIs
Each component also provides some other APIs:

setState()
forceUpdate()

Class Properties
defaultProps
displayName

Instance Properties
props
state

Commonly Used Life cycle Methods

render() The render() method is the only required method in a class component.

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

If you don’t initialize state and you don’t bind methods, you don’t need to implement a constructor for your React component.

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

6. What is the difference between Dom and virtual Dom in React js?

DOM is the acronym for Document Object Model. Dom is also called HTML DOM as it is an abstraction of structured code called HTML for web developers. Dom and HTML code are interrelated as the elements of HTML are known as nodes of DOM. It defines a structure where users can create, alter, modify documents and the content present in it. So while HTML is a text, DOM is an in-memory representation of this text.

Virtual DOM is an abstraction of abstraction as it has been derived from HTML DOM. It is a representation of DOM objects like a lightweight copy. The virtual DOM was not invented by React, it is only used and provided for free.

 

7. How ReactJS Handling Events

Handling events with React elements is very similar to handling events on DOM elements. There are some syntactic differences:

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

For example, the HTML:

<button onclick="activateLasers()">
          Activate Lasers
</button>

In React:

<button onClick={activateLasers}>
          Activate Lasers
</button>

Another difference is that you cannot return false to prevent default behavior in React. You must call preventDefault explicitly. For example, with plain HTML, to prevent the default link behavior of opening a new page, you can write:

<a href="#" onclick="console.log('The link was clicked.'); return false">
    Click me
</a>

In React, this could instead be:

function ActionLink() {
   function handleClick(e) {
               e.preventDefault();
               console.log('The link was clicked.');
    }

return (
         <a href="#" onClick={handleClick}>
                 Click me
         </a>
     );
}

Here, e is a synthetic event. React defines these synthetic events according to the W3C spec, so you don’t need to worry about cross-browser compatibility.

 

8. What is Synthetic Event

Synthetic Event is a cross-browser wrapper around the browser’s native event. Your event handlers will be passed instances of Synthetic Event. It has the same interface as the browser’s native event, including stopPropagation() and preventDefault(), except the events work identically across all browsers.
Every SyntheticEvent object has the following attributes:

  • boolean bubbles
  • boolean cancelable
  • DOMEventTarget currentTarget
  • boolean defaultPrevented
  • number eventPhase
  • boolean isTrusted
  • DOMEvent nativeEvent
  • void preventDefault()
  • boolean isDefaultPrevented()
  • void stopPropagation()
  • boolean isPropagationStopped()
  • DOMEventTarget target
  • number timeStamp
  • string type

Below is a simple example of how to listen for a click event in react

import React, { Component } from 'react';

class ShowMsg extends Component {

showMsg() {
return { react: "hello react" }
}

render() {
return (
<button onClick={this.showMsg}>show msg </button>
);
}
}

export default showMsg;

 

What is Event Pooling

The Synthetic Event is pooled. This means that the Synthetic Event object will be reused and all properties will be nullified after the event callback has been invoked. This is for performance reasons. As such, you cannot access the event in an asynchronous way.

function onClick(event) {
console.log(event); // => nullified object.
console.log(event.type); // => "click"
const eventType = event.type; // => "click"

setTimeout(function() {
console.log(event.type); // => null
console.log(eventType); // => "click"
}, 0);

// Won't work. this.state.clickEvent will only contain null values.
this.setState({clickEvent: event});

// You can still export event properties.
this.setState({eventType: event.type});
}

 

 

9. Explain the difference between functional and class components.

Functional components are those components that returns React elements as a result. These are just simple old JavaScript functions. React 0.14 has given a new shortcut for creating simple stateless components that are known as functional components. These components make use of easy JavaScript functions.
Class components –  These components make use of plain old java objects for creating pages, mixins, etc in an identical way. Using React’s create a class factory method, a literal is passed in defining the methods of a new component.

10. What are refs in React? When to use it.

React supports a special attribute that you can attach to any component.ref is used to store the reference of element or component returned by the component render() configuration function.Refs should be avoided in most cases, however, they can be useful when we need DOM measurements or to add methods to the components.

Refs can be used in the following cases

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

11. What are stateless components in React?

Stateless components are components that don’t have any state. When something is stateless, it calculates its internal state but it never directly mutates it.For creating a stateless components No class and this keyword is needed.You can create a stateless components using plain functions or Es6 arrow function.

//In Es6
const = (props) =>

 

12. What is the difference between State and props in ReactJs?

The most important difference between state and props is that props are passed from a parent component, but state is managed by the component itself. A component cannot change its props, but it can change its state. To do so, it must call this.setState(). Only components defined as classes can have state.

props are inputs to a React component. They are data passed down from a parent component to a child component.
Remember that props are readonly. They should not be modified in any way.Props are shorthand for properties.they are very similar to an argument is passed to a pure javascript function.If you need to modify some value in response to user input or a network response, use state instead.

For example:

<Welcome>Hello world!</Welcome>
The string Hello world! is available in props.children in the Welcome component:

function Welcome(props) {
return <p>{props.children}</p>;
}
For components defined as classes, use this.props.children:

class Welcome extends React.Component {
render() {
return <p>{this.props.children}</p>;
}
}

 

State are used to create dynamic and interactive components in React.State is backbone of react component that makes react application alive and determines how a component renders and communicate. For each particular piece of changing data, there should be just one component that “owns” it in its state.

 

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.