preface

The popularity of the React front-end framework shows no signs of abating, with developers still in short supply in many cities across the country. For inexperienced developers (or those who have been out of work for a while), demonstrating your knowledge during the interview stage can be daunting.

In this article, we’ll explore 18 must-have interview questions that cover a range of knowledge critical to understanding and using React technology effectively. For each question, I summarize the answers and provide links to related learning resources where you can find more information.

What is the virtual DOM?

answer

The virtual DOM is an in-memory representation of the actual HTML elements that make up the application’s user interface. When a component is rerendered, the virtual DOM compares the changes to its DOM model to create a list of updates to apply. The main advantage is that it is efficient, requiring minimal changes to the actual DOM without having to re-render large chunks.

Further reading

  • Understanding the Virtual DOM
  • Virtual DOM Interpretation

2. What is JSX?

answer

JSX is an extension of JavaScript syntax that allows you to write HTML-like code. It can be compiled into regular JavaScript function calls, providing a better way to create component tags.

The JSX code is as follows:

<div className="sidebar" />
Copy the code

It converts to the following JS code:

React.createElement(
  'div',
  {className: 'sidebar'})Copy the code

Further reading

  • JSX profile
  • Deep understanding of JSX

3. What is the difference between class components and function components?

answer

Prior to React 16.8 (which introduced hooks), class-based components were used to create components that needed to maintain internal state or utilize lifecycle methods (that is, componentDidMount and shouldComponentUpdate). The class-based Component is the ES6 class, which extends the React Component class and at least implements the Render () method.

Types of components:

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

The function component is stateless (again, smaller than React 16.8 version) and returns the output to render. Their preferred way to render the UI is to rely only on properties, because they are simpler and perform better than class-based components.

Function components:

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

Note: The introduction of hooks in the React 16.8 release means that these differences no longer apply (see questions 14 and 15).

Further reading

  • React compares functional components to class components
  • Compare functions with class components in React

4. What is the function of keys in React?

Keys are an auxiliary identifier used by React to track which elements in a list were changed, added, or removed.

When rendering collections in React, adding keywords to each repeating element is important to help React track associations between elements and data. Key should be a unique ID, preferably a UUID or some other unique string in the collection item:

<ul>
  {todos.map((todo) = >
    <li key={todo.id}>
      {todo.text}
    </li>
  )};
</ul>
Copy the code

When adding and removing items from a collection, not using keys or using indexes as keys can lead to strange behavior.

Further reading

  • List & key
  • React key property

5. What is the difference between props and state?

answer

Props is the data passed from the parent component to the component. They should not be changed, but should only be displayed or used to calculate other values. State is the internal data of a component that can be modified over the lifetime of the component and maintained between re-renders.

Further reading

  • Understand Props & State in depth

6. Why call setState instead of directly changing state?

answer

If you try to change the state of the component directly, React won’t know that it needs to rerender the component. React updates the component’s UI by using the setState() method.

In addition, you can talk about how status updates are not guaranteed to be synchronous. If you need to update the component’s state based on another state (or property), pass a function to setState() that takes state and props as its two arguments:

this.setState((state, props) = > ({
  counter: state.counter + props.increment
}));
Copy the code

Further reading

  • Use State correctly

7. How do I limit, or make necessary, the type of value passed as props?

answer

To type check the props of a component, you can use the prop-types package (previously included as part of React prior to version 15.5) to declare the expected value types and whether the prop is needed:

import PropTypes from 'prop-types';

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

Greeting.propTypes = {
  name: PropTypes.string
};
Copy the code

Further reading

  • Use PropTypes for type checking

8. What is Prop Drilling and how to avoid it?

Prop Drilling (also called threading) is what happens when you need to pass data down from parent components to components lower down in the hierarchy, “drilling” through other components that don’t need props themselves in addition to passing them.

Sometimes, drilling can be avoided by refactoring components, avoiding premature decomposition into smaller components, and keeping the common state in the closest common parent. If you need to share state between components deep in the component tree/with each other, you can use the React Context API or a dedicated state management library (such as Redux).

Further reading

  • Prop drilling,

9. React Context?

answer

React provides a context API to address the issue of sharing state between multiple components within an application. Before introducing context, the only option is to introduce a separate state management library, such as Redux. However, many developers feel that Redux introduces a lot of unnecessary complexity, especially for smaller applications.

Further reading

  • Context in the React document
  • How to replace Redux with React Hooks and Context APIS

What is a Redux?

answer

Redux is a third-party state management library for React that was created before the context API existed. It is based on the concept of a state container called a store from which components can receive data as props. The only way to update the repository is to send an operation to the repository, which is passed to a Reducer. Reducer receives the actions and current state and returns a new state that triggers a re-rendering of the subscribed components.

Further reading

  • Introduction to story
  • Dig deeper into Redux

11. What is the most common way to style React applications?

answer

There are several ways to style the React component, each with its own advantages and disadvantages. The main points to mention are:

  • Inline style: Good for prototyping, but limited (for example, no pseudo-class style)
  • Class-based CSS styles: More efficient than inline styles, and familiar to developers new to React
  • CSS in JS Styles: There are many libraries that allow styles to be declared as JavaScript within components, making styles more code-like.

Further reading

  • How do I style the React component

12. What is the difference between a controlled component and an uncontrolled component?

answer

In HTML documents, many form elements (such as < SELECT >, < textrArea >, ) keep their state. Uncontrolled components treat the DOM as the real source of these input states. In controlled components, internal state is used to track element values. React rerenders the input when the value changes.

Uncontrolled components are useful when integrating with non-React code (for example, if you need to support some kind of jQuery form plug-in).

Further reading

  • The controlled components
  • Uncontrolled component
  • Controlled input and uncontrolled input

13. What is the lifecycle approach?

answer

Class-based components can declare special methods that are called at certain points in their life cycle, such as when they are loaded (rendered into the DOM) and when they are unloaded. For example, they are useful for setting up and dismantling things a component might need, setting timers, or binding to browser events.

You can implement the following lifecycle methods in a component:

  • ComponentWillMount: Called after creating a component but before rendering it into the DOM
  • ComponentDidMount: called after the first render; The COMPONENT’s DOM element is now available
  • ComponentWillReceiveProps: when the attribute update call
  • ShouldComponentUpdate: This method prevents re-rendering to optimize performance when new props are received
  • ComponentWillUpdate: Called when new props are received and ComponentUpdate returns true
  • ComponentDidUpdate: Called after a component is updated
  • ComponentWillUnmount: Called before the component is removed from the DOM, allowing you to clean up things like event listeners.

When working with functional components, you can use the useEffect hook to replicate the lifecycle behavior.

Further reading

  • React lifecycle method schematic
  • Component life cycle

14. What are React hooks?

answer

Hooks are React’s attempt to bring the benefits of class-based components (that is, internal state and lifecycle methods) to functional components.

Further reading

  • Learn React hooks in 5 minutes
  • React Hooks: How to start and build quickly

15. What advantages do React hooks have?

answer

Introducing hooks into React has several obvious benefits:

  • Class-based components, lifecycle hooks, and the this keyword are not required
  • It makes it easier to reuse logic by abstracting public functions into custom hooks
  • Make your code more readable and testable by being able to separate the logic from the components themselves

Further reading

  • The benefits of React Hooks
  • The benefits of React Hooks versus older reusable logic methods

16. Why does virtual DOM improve performance?

answer

  • The virtual DOM is equivalent to adding a cache between JS and the real DOM. Dom diff algorithm is used to avoid unnecessary DOM operations, thus improving performance.
  • Using JavaScript object structure to represent the DOM tree structure; Then use this tree to build a real DOM tree and plug it into the document to reconstruct a new object tree when the state changes. The new tree is then compared with the old tree to record the differences between the two trees. Apply the differences recorded in 2 to the actual DOM tree built in Step 1, and the view is updated.

Further reading

  • How to understand the virtual DOM

React Diff

answer

  • Break down the tree structure by hierarchy, comparing only peer elements.
  • Each unit of the list structure adds a unique key attribute for easy comparison.
  • React will only match components of the same class.
  • Merge operations. When calling component’s setState method, React marks it as dirty until the end of each event loop. React checks for all components marked dirty to be redrawn.
  • Select subtree rendering. Developers can rewrite shouldComponentUpdate to improve diff performance.

Further reading

  • The incredible React Diff
  • Teach you how to React diff

18. What does refs do in React?

answer

Refs is a handle to a DOM element or component instance that React provides us with secure access.

We can add the ref attribute to the element and then accept the element’s handle to the DOM tree in the callback function, which is returned as the first argument to the callback function:

class CustomForm extends Component {
  handleSubmit = () = > {
    console.log("Input Value: ".this.input.value)
  }
  render () {
    return (
      <form onSubmit={this.handleSubmit}>
        <input
          type='text'
          ref={(input)= > this.input = input} />
        <button type='submit'>Submit</button>
      </form>)}}Copy the code

The input field in the code above contains a ref attribute that declares a callback function that accepts the DOM element corresponding to the input, which we bind to the this pointer for use in other class functions.

It is also worth noting that refs are not exclusive to class components. Functional components can also use closures to temporarily store their values:

function CustomForm ({handleSubmit}) {
  let inputElement
  return (
    <form onSubmit={()= > handleSubmit(inputElement.value)}>
      <input
        type='text'
        ref={(input)= > inputElement = input} />
      <button type='submit'>Submit</button>
    </form>)}Copy the code

Further reading

  • When to use Refs

conclusion

While this isn’t a comprehensive list (React is evolving), there are many facets to the issues. Understanding these issues will give you a good idea of the library and some of its latest changes. It is suggested that further reading will help consolidate your comprehension so that you can demonstrate knowledge from the simple to the deep.

React! Good luck!

15 React Interview Questions with Solutions

Like can pay attention to the author public number [lazy code farmers], we learn together progress…