1. How to apply validation on props in React?

    When the application is running in development mode, React will automatically check all props that we set on components to make sure they have correct type. If the type is incorrect, React will generate warning messages in the console. It's disabled in production mode due to performance impact. The mandatory props are defined with isRequired.

    The set of predefined prop types:

    1. PropTypes.number
    2. PropTypes.string
    3. PropTypes.array
    4. PropTypes.object
    5. PropTypes.func
    6. PropTypes.node
    7. PropTypes.element
    8. PropTypes.bool
    9. PropTypes.symbol
    10. PropTypes.any

    We can define propTypes for User component as below:

    import React from 'react'
    import PropTypes from 'prop-types'
    
    class User extends React.Component {
      static propTypes = {
        name: PropTypes.string.isRequired,
        age: PropTypes.number.isRequired
      }
    
      render() {
        return (
          <>
            <h1>{`Welcome, ${this.props.name}`}</h1>
            <h2>{`Age, ${this.props.age}`}</h2>
          </>
        )
      }
    }
    

    Note: In React v15.5 PropTypes were moved from React.PropTypes to prop-types library.

    The Equivalent Functional Component

    import React from 'react'
    import PropTypes from 'prop-types'
    
    function User() {
      return (
        <>
          <h1>{`Welcome, ${this.props.name}`}</h1>
          <h2>{`Age, ${this.props.age}`}</h2>
        </>
      )
    }
    
    User.propTypes = {
        name: PropTypes.string.isRequired,
        age: PropTypes.number.isRequired
      }
    
  2. What are the advantages of React?

    Below are the list of main 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.

  3. What are the limitations of React?

    Apart from the advantages, there are few limitations of React too,

    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.

  4. What are error boundaries in React v16?

    Error boundaries are components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed.

    A class component becomes an error boundary if it defines a new lifecycle method called componentDidCatch(error, info) or static getDerivedStateFromError() :

    class ErrorBoundary extends React.Component {
      constructor(props) {
        super(props)
        this.state = { hasError: false }
      }
    
      componentDidCatch(error, info) {
        // You can also log the error to an error reporting service
        logErrorToMyService(error, info)
      }
    
      static getDerivedStateFromError(error) {
         // Update state so the next render will show the fallback UI.
         return { hasError: true };
       }
    
      render() {
        if (this.state.hasError) {
          // You can render any custom fallback UI
          return <h1>{'Something went wrong.'}</h1>
        }
        return this.props.children
      }
    }
    

    After that use it as a regular component:

    <ErrorBoundary>
      <MyWidget />
    </ErrorBoundary>
    
  5. How error boundaries handled in React v15?

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

  6. What are the recommended ways for static type checking?

    Normally we use PropTypes library (React.PropTypes moved to a prop-types package since React v15.5) for type checking in the React applications. For large code bases, it is recommended to use static type checkers such as Flow or TypeScript, that perform type checking at compile time and provide auto-completion features.

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

    1. render()

    2. hydrate()

    3. unmountComponentAtNode()

    4. findDOMNode()

    5. createPortal()

  8. What is the purpose of 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 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.

  9. What is ReactDOMServer?

    The ReactDOMServer object enables you to render components to static markup (typically used on node server). This object is mainly used for server-side rendering (SSR). The following methods can be used in both the server and browser environments:

    1. renderToString()
    2. renderToStaticMarkup()

    For example, you generally run a Node-based web server like Express, Hapi, or Koa, and you call renderToString to render your root component to a string, which you then send as response.

    // using Express
    import { renderToString } from 'react-dom/server'
    import MyPage from './MyPage'
    
    app.get('/', (req, res) => {
      res.write('<!DOCTYPE html><html><head><title>My Page</title></head><body>')
      res.write('<div id="content">')
      res.write(renderToString(<MyPage/>))
      res.write('</div></body></html>')
      res.end()
    })
    
  10. How to use innerHTML in 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 a __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()} />
    }