What is the recommended way for naming components in React?

The recommended way to name the component is by reference instead of just using displayName.

In the below example the component is named as AccountApp instead of displayName:

export default class AccountApp extends React.Component {

  // …

}

What is the recommended way of ordering methods in component class?

Below are the recommended methods from mounting to rendering stage:

  1. static methods
  2. constructor()
  3. getChildContext()
  4. componentWillMount()
  5. componentDidMount()
  6. componentWillReceiveProps()
  7. shouldComponentUpdate()
  8. componentWillUpdate()
  9. componentDidUpdate()
  10. componentWillUnmount()
  11. click handlers or event handlers like onClickSubmit() or onChangeDescription()
  12. getter methods for render like getSelectReason() or getFooterContent()
  13. optional render methods like renderNavigation() or renderProfilePicture()
  14. render()

What does switching component mean?

switching component is a component that renders one of many components. We need to use object to map prop values to components.

Why we need to pass a function to setState()?

The reason behind for this is that setState() is an asynchronous operation. React batches state changes for performance reasons, so the state may not change immediately after setState() is called. That means you should not rely on the current state when calling setState() since you can’t be sure what that state will be. The solution is to pass a function to setState(), with the previous state as an argument. By doing this you can avoid issues with the user getting the old state value on access due to the asynchronous nature of setState().

Let’s say the initial count value is zero. After three consecutive increment operations, the value is going to be incremented only by one.

// assuming this.state.count === 0

this.setState({ count: this.state.count + 1 })

this.setState({ count: this.state.count + 1 })

this.setState({ count: this.state.count + 1 })

// this.state.count === 0, not 3

If we pass a function to setState(), the count gets incremented correctly.

this.setState((prevState, props) => ({

  count: prevState.count + props.increment

}))

// this.state.count === 3 as expected

(OR)

Why function is preferred over object for setState()?

React may batch multiple setState() calls into a single update for performance. Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.

This counter example will fail to update as expected:

// Wrong

this.setState({

  counter: this.state.counter + this.props.increment,

})

The preferred approach is to call setState() with function rather than object. That function will receive the previous state as the first argument, and the props at the time the update is applied as the second argument.

// Correct

this.setState((prevState, props) => ({

  counter: prevState.counter + props.increment

}))

What is strict mode in React?

React.StrictMode is a useful component for highlighting potential problems in an application. Just like <Fragment>, <StrictMode> does not render any extra DOM elements. It activates additional checks and warnings for its descendants. These checks apply for development mode only.

import React from ‘react’

function ExampleApplication() {

  return (

    <div>

      <Header />

      <React.StrictMode>

        <div>

          <ComponentOne />

          <ComponentTwo />

        </div>

      </React.StrictMode>

      <Header />

    </div>

  )

}

In the example above, the strict mode checks apply to <ComponentOne> and <ComponentTwo> components only.

What are React Mixins?

Mixins are a way to totally separate components to have a common functionality. Mixins should not be used and can be replaced with higher-order components or decorators.

One of the most commonly used mixins is PureRenderMixin. You might be using it in some components to prevent unnecessary re-renders when the props and state are shallowly equal to the previous props and state:

const PureRenderMixin = require(‘react-addons-pure-render-mixin’)

const Button = React.createClass({

  mixins: [PureRenderMixin],

  // …

})

Why is isMounted() an anti-pattern and what is the proper solution?

The primary use case for isMounted() is to avoid calling setState() after a component has been unmounted, because it will emit a warning.

if (this.isMounted()) {

  this.setState({…})

}

Checking isMounted() before calling setState() does eliminate the warning, but it also defeats the purpose of the warning. Using isMounted() is a code smell because the only reason you would check is because you think you might be holding a reference after the component has unmounted.

An optimal solution would be to find places where setState() might be called after a component has unmounted, and fix them. Such situations most commonly occur due to callbacks, when a component is waiting for some data and gets unmounted before the data arrives. Ideally, any callbacks should be canceled in componentWillUnmount(), prior to unmounting.

What are the Pointer Events supported in React?

Pointer Events provide a unified way of handling all input events. In the old days we had a mouse and respective event listeners to handle them but nowadays we have many devices which don’t correlate to having a mouse, like phones with touch surface or pens. We need to remember that these events will only work in browsers that support the Pointer Events specification.

The following event types are now available in React DOM:

onPointerDown

onPointerMove

onPointerUp

onPointerCancel

onGotPointerCapture

onLostPointerCapture

onPointerEnter

onPointerLeave

onPointerOver

onPointerOut

Why should component names start with capital letter?

If you are rendering your component using JSX, the name of that component has to begin with a capital letter otherwise React will throw an error as unrecognized tag. This convention is because only HTML elements and SVG tags can begin with a lowercase letter.

class SomeComponent extends Component {

 // Code goes here

}

You can define component class which name starts with lowercase letter, but when it’s imported it should have capital letter. Here lowercase is fine:

class myComponent extends Component {

  render() {

    return <div />

  }

}

export default myComponent

While when imported in another file it should start with capital letter:

import MyComponent from ‘./MyComponent’

What are the exceptions on React component naming?

The component names should start with a uppercase letter but there are few exceptions on this convention. The lowercase tag names with a dot (property accessors) are still considered as valid component names. For example the below tag can be compiled to a valid component,

     render() {

          return (

            <obj.component/> // `React.createElement(obj.component)`

          )

    }

Are custom DOM attributes supported in React v16?

Yes. In the past, React used to ignore unknown DOM attributes. If you wrote JSX with an attribute that React doesn’t recognize, React would just skip it.

For example, let’s take a look at the below attribute:

<div mycustomattribute={‘something’} />

Would render an empty div to the DOM with React v15:

<div />

In React v16 any unknown attributes will end up in the DOM:

<div mycustomattribute=’something’ />

This is useful for supplying browser-specific non-standard attributes, trying new DOM APIs, and integrating with opinionated third-party libraries.

What is the difference between constructor and getInitialState?

You should initialize state in the constructor when using ES6 classes, and getInitialState() method when using React.createClass().

Using ES6 classes:

class MyComponent extends React.Component {

  constructor(props) {

    super(props)

    this.state = { /* initial state */ }

  }

}

Using React.createClass():

const MyComponent = React.createClass({

  getInitialState() {

    return { /* initial state */ }

  }

})

Note: React.createClass() is deprecated and removed in React v16. Use plain JavaScript classes instead.

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

What is the difference between super() and super(props) in React using ES6 classes?

When you want to access this.props in constructor() then you should pass props to super() method.

Using super(props):

class ProductList extends React.Component {

  constructor(props) {

    super(props)

    console.log(this.props) // { name: ‘John’, … }

  }

}

Using super():

class ProductList extends React.Component {

  constructor(props) {

    super()

    console.log(this.props) // undefined

  }

}

Outside constructor() both will display same value for this.props.

How to loop inside JSX?

You can simply use Array.prototype.map with ES6 arrow function syntax.

For example, the items array of objects is mapped into an array of components:

<tbody>

  {items.map(item => <SomeComponent key={item.id} name={item.name} />)}

</tbody>

But you can’t iterate using for loop:

<tbody>

  for (let i = 0; i < items.length; i++) {

    <SomeComponent key={items[i].id} name={items[i].name} />

  }

</tbody>

This is because JSX tags are transpiled into function calls, and you can’t use statements inside expressions. This may change thanks to do expressions which are stage 1 proposal.

How do you access props in attribute quotes?

React (or JSX) doesn’t support variable interpolation inside an attribute value. The below representation won’t work:

<img className=’image’ src=’images/{this.props.image}’ />

But you can put any JS expression inside curly braces as the entire attribute value. So the below expression works:

<img className=’image’ src={‘images/’ + this.props.image} />

Using template strings will also work:

<img className=’image’ src={`images/${this.props.image}`} />

What is React proptype array with shape?

If you want to pass an array of objects to a component with a particular shape then use React.PropTypes.shape() as an argument to React.PropTypes.arrayOf().

ReactComponent.propTypes = {

  arrayWithShape: React.PropTypes.arrayOf(React.PropTypes.shape({

    color: React.PropTypes.string.isRequired,

    fontSize: React.PropTypes.number.isRequired

  })).isRequired

}

How to conditionally apply class attributes?

You shouldn’t use curly braces inside quotes because it is going to be evaluated as a string.

<div className=”btn-panel {this.props.visible ? ‘show’ : ‘hidden’}”>

Instead you need to move curly braces outside (don’t forget to include spaces between class names):

<div className={‘btn-panel ‘ + (this.props.visible ? ‘show’ : ‘hidden’)}>

Template strings will also work:

<div className={`btn-panel ${this.props.visible ? ‘show’ : ‘hidden’}`}>

What is the difference between React and ReactDOM?

The react package contains React.createElement(), React.Component, React.Children, and other helpers related to elements and component classes. You can think of these as the isomorphic or universal helpers that you need to build components. The react-dom package contains ReactDOM.render(), and in react-dom/server we have server-side rendering support with ReactDOMServer.renderToString() and ReactDOMServer.renderToStaticMarkup().

Why ReactDOM is separated from React?

The React team worked on extracting all DOM-related features into a separate library called ReactDOM. React v0.14 is the first release in which the libraries are split. By looking at some of the packages, react-native, react-art, react-canvas, and react-three, it has become clear that the beauty and essence of React has nothing to do with browsers or the DOM.

To build more environments that React can render to, React team planned to split the main React package into two: react and react-dom. This paves the way to writing components that can be shared between the web version of React and React Native.

How to use React label element?

If you try to render a <label> element bound to a text input using the standard for attribute, then it produces HTML missing that attribute and prints a warning to the console.

<label for={‘user’}>{‘User’}</label>

<input type={‘text’} id={‘user’} />

Since for is a reserved keyword in JavaScript, use htmlFor instead.

<label htmlFor={‘user’}>{‘User’}</label>

<input type={‘text’} id={‘user’} />

How to combine multiple inline style objects?

You can use spread operator in regular React:

 <button style={{…styles.panel.button, …styles.panel.submitButton}}>{‘Submit’}</button>

If you’re using React Native then you can use the array notation:

<button style={[styles.panel.button, styles.panel.submitButton]}>{‘Submit’}</button>

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

You can listen to the resize event in componentDidMount() and then update the dimensions (width and height). You should remove the listener in componentWillUnmount() method.

class WindowDimensions extends React.Component {

  constructor(props){

    super(props);

    this.updateDimensions = this.updateDimensions.bind(this);

  }

  componentWillMount() {

    this.updateDimensions()

  }

  componentDidMount() {

    window.addEventListener(‘resize’, this.updateDimensions)

  }

  componentWillUnmount() {

    window.removeEventListener(‘resize’, this.updateDimensions)

 }

 updateDimensions() {

    this.setState({width: window.innerWidth, height: window.innerHeight})

 }

 render() {

    return <span>{this.state.width} x {this.state.height}</span>

 }

}

One thought on “React Advanced Interview Questions”

Leave a Reply