The most complete React interview questions

1. What is virtual DOM?

The virtual DOM is the representation of the real DOM in memory. The representation of ul is stored in memory and synchronized with the actual DOM. This is a step that occurs when the rendering function is called and the element is displayed on the screen. The whole process is called reconcile

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

Class components can use other features, such as state and life cycle hooks, and he has this

Function components can only receive props to render to the page, stateless components, without this, cannot use lifecycle hooks

The performance of function components is higher than that of class components, because class components need to be instantiated, while function components can be directly executed to get the returned results. In order to improve performance, try to use function components

3. What is refs in react?

Refs provide a way to access DOM nodes or React elements created in the render method. In a typical data flow, props is the only way for parent-child components to interact. If you want to modify a child component, you need to re-render it with new props. In some cases, outside the typical data flow, children are forced to modify, and refs can be used at this time

We can add a ref attribute to the component to use, which is a callback function that receives as its first parameter the underlying DOM element or component mount instance

The input element has a ref attribute whose value is a function that takes the actual DOM element input and places it on the instance so it can be accessed inside the  handleSubmit function

Often misunderstood only works with class components  refs, but refscan also be used with function components by leveraging closures in JS

4. How to handle events in react?

In order to solve cross-browser compatibility issues, SyntheticEvent the instance will be passed to your event handler function, SyntheticEventwhich is React's cross-browser browser-native event wrapper, and it also has the same interface as browser-native events, including  stopPropagation() and  preventDefault().

Interestingly enough, React doesn't actually attach events to the child nodes themselves. React listens to all events at the top level with a single event listener. This is good for performance and means React doesn't need to keep track of event listeners when updating the DOM.

5. What is the difference between state and props?

The same point: they are all ordinary js objects, they contain information that affects the rendering output

The difference: state is that the component manages data by itself, controls its own state, and is variable

props is the data parameter passed in from the outside, immutable

A component without a state is called a stateless component, and a component with a state is called a stateful component

Use more props and less state

6. How to create refs?

Created by React.createRef(), and attached to the react element through the ref attribute, in the construction component,

Typically will  Refs be assigned to instance properties so that they can be referenced throughout the component.

7. What is a higher-order component?

Higher-order components (HOCs) are functions that take a component and return a new component. Basically, this is a pattern that was derived from React's composition feature, called pure components , because they can accept any dynamically provided child components, but do not modify or duplicate any behavior in the input components

HOCs can be used for many use cases as follows

  • Code reuse, logic and bootstrapping abstraction
  • render hijacking
  • state abstraction and operations
  • props processing

8. What is the function of calling super in the constructor and passing in props as parameters?

super() Subclass constructors cannot use references until the method  is called  this, and this is also true for ES6 subclasses. The main reason for passing  props parameters to  the call is to be able to get passed in  super() in the subconstructor .this.propsprops

props The behavior of is only different inside the constructor, it's the same outside the constructor

9. What is a controlled component?

In HTML, form elements such as  <input>, <textarea>and <select>usually maintain their own state and are updated based on user input. When the user submits the form, the values ​​from the above elements will be sent with the form.

React works differently. The component containing the form will keep track of input values ​​in its state and onChangere-render the component every time the callback function (for example) fires because the state is updated. Input form elements whose value is controlled by React in this way are called controlled components.

10. How to React.createElement?

const element = (

  <h1 className="greeting">

    Hello, world!

  </h1>

)
const element = React.createElement(

  'h1',

  {className: 'greeting'},

  'Hello, world!'

);

11. What is jsx?

When react was first released, a new js dialect, jsx, was also introduced to embed the original HTML template into the JS code. JSX code itself cannot be read by the browser and must be converted to traditional JS using tools such as and Babel. webpackMany developers can use JSX without realizing it because it is already integrated with React

12. Why not update the state directly?

If you try to update the state directly, the component will not be re-rendered

The state needs to be updated using the setState() method, which updates the state object, and when the state changes, the component responds by re-rendering

13. What are the different phases of React component life cycle?

  1. Initialization : In this phase, the component is ready to set initialization state and default properties.
  2. Mounting : The react component is ready to be mounted into the browser DOM. This phase includes componentWillMountand componentDidMountlifecycle methods.
  3. Updating : In this phase, the component is updated in two ways, sending new props and state. This phase includes shouldComponentUpdate, componentWillUpdateand componentDidUpdatelifecycle methods.
  4. Unmounting : At this stage, the component is no longer needed and it is unmounted from the browser DOM. This phase contains  componentWillUnmount lifecycle methods.

In addition to the above four common life cycles, there is also an error handling phase:

Error Handling : At this stage, the component will be called whenever an error occurs during rendering, in a lifecycle method, or in any child component's constructor. This phase contains  componentDidCatch the lifecycle methods.

14. What are the react lifecycle methods?

  • componentWillMount: Executed before rendering, used for App-level configuration in the root component.
  • componentDidMount: Executed after the first rendering, where you can make AJAX requests, DOM operations or status updates, and set event listeners.
  • componentWillReceiveProps: It will not be executed during initialization render, it will be triggered when the component receives a new state (Props), generally used for re-rendering of child components when the state of the parent component is updated
  • shouldComponentUpdate: Determines whether to update the component. By default, it returns true.  This can be returned if it is determined that  the component does not need to be re-rendered after state or  after an update , which is a way to improve performance.propsfalse
  • componentWillUpdate: Executed before shouldComponentUpdatereturning  true the precondition that determines that the component is to be updated.
  • componentDidUpdate: It is mainly used to update the DOM in response propsor statechanges.
  • componentWillUnmount: It is used to cancel any network requests, or remove all event listeners associated with the component.

15. What are the three dots(...) used for in React?

 The spread operator, or spread operator, is handy for creating new objects with most of the properties of existing objects, and is often used when updating state

16. What are the benefits of using React Hooks?

Hooks are a new addition in React 16.8. stateThey allow using and other React features without writing classes . Using Hooks, stateful logic can be extracted from components so that it can be tested and reused independently. Hooks allow us to reuse stateful logic without changing the component hierarchy, making it easy to share Hooks between many components or with the community

What problem do hooks solve?

        Feature issues in class components can be used in function components

17: What is in React  useState() ?

useState is a built-in React Hook. useState(0) Returns a tuple where the first argument countis the current state of the counter, setCounter providing methods to update the state of the counter.

We can use the method to update the count state anywhere setCounter- in this case, we setCountcan use it inside the function to do more things, using Hooks, we can keep our code more functional, and avoid excessive use based on class components

Define the data of the state, the parameter is the initialized data, and the return value is two values ​​1. Initialization value, 2. Modification method

The method modified in useState is asynchronous

  1. Data monitoring with the help of useEffect

  2. You can define the method of Hooks by yourself, and the logic can be returned inside the method

18. What is StrictMode in React?

React StrictModeis an auxiliary component that can help us write better react components, which can be used to <StrictMode />wrap a set of components, and can help us check the following:

  • Verify that internal components follow certain recommended practices, and warn you in the console if they don't.
  • Verify that a deprecated method is used, and if so, a warning will be given in the console.
  • Prevent some side effects by identifying potential risks.

19. Why do class methods need to be bound to a class instance?

In js, the value of this changes according to the current context. In React class component methods, developers usually want this to refer to the current instance of the crime, so it is necessary to bind these methods to the instance

20. What is prop drilling and how to avoid it?

When building a React application, nest components at multiple levels to consume data provided by another nested component. The easiest way to do this is to  prop pass a prop down from each component, from the source component to deeply nested components. This is called prop drilling .

prop drillingThe main disadvantage is that components that do not otherwise require data become unnecessarily complex and difficult to maintain.

To avoid that prop drilling, a common way is to use React Context . By defining components that provide data Provider, and allowing nested components  to use contextual data through Consumercomponents or HooksuseContext

21. Describe Flux and MVC?

The traditional MVC pattern works pretty well for separating data (Model), UI (View, and logic (Controller), but MVC architectures often suffer from two main problems:

Insufficient data flow : Cascading updates that occur across views often lead to chaotic webs of events that are difficult to debug.

Lack of Data Integrity : Model data can mutate anywhere, producing unpredictable results throughout the UI.

Complex UIs using the Flux pattern no longer suffer from cascading updates, any given React component is able to  store rebuild its state based on the data provided. The Flux pattern also enforces data integrity by restricting direct access to shared data

22. What is the difference between controlled components and uncontrolled components?

  • A controlled component is a component in a React control and is the only source of truth for form data.
  • Uncontrolled components are where form data is processed by the DOM, not in React components.

Although unmanaged components are usually easier to implement because you can simply use them refsto get the value from the DOM, it is generally recommended to prefer controlled components over unmanaged components.

The main reason for this is that controlled components support on-the-fly field validation, allow conditionally disabling/enabling buttons, force input formatting

23.  What is React Context?

Context Provides a way to pass data through the component tree, avoiding the need to manually pass  props properties at each level

24. What is React Fiber?

Fiber  is the new coordination engine or reimplementation of the core algorithm in React 16. Its main goal is to support incremental rendering of the virtual DOM. The goal of React Fiber  is to improve its usability for animation, layout, gestures, pause, abort or reuse, and to assign priorities to different types of updates, as well as new concurrency primitives.

The goal of React Fiber is to enhance its applicability in areas such as animation, layout, and gestures. Its main feature is incremental rendering: the ability to split rendering work into chunks and spread it across multiple frames.

25. How to apply validation on Props in ReactJS?

When the application is running in development mode, React will automatically check everything we set on the components  propsto make sure they have the correct data types. For incorrect types, a warning message is generated in the console in development mode, and disabled in production mode due to performance impact. Mandatory  props by  isRequireddefinition.

The following are a set of predefined prop types:

  • React.PropTypes.string
  • React.PropTypes.number
  • React.PropTypes.func
  • React.PropTypes.node
  • React.PropTypes.bool

26. What is the difference between using constructor and getInitialState in React?

The difference between constructor and getInitialStateis the difference between ES6and ES5itself. When using ES6a class, it should be initialized in the constructor stateand methods React.createClassshould be defined when used getInitialState.

27. Will Hooks replace  render props and higher-order components?

render propsand higher-order components render only one child component. The React team believes that Hooks are an easier way to serve this use case.

Both patterns still have their place (for example, a virtual  scroller component might have one  renderItem prop, or a visual container component might have its own DOM structure). But in most cases, Hooks are enough and can help reduce nesting in the tree

28. How to avoid re-rendering of components?

One of the most common problems in React is components re-rendering unnecessarily. React provides two methods that are useful in these situations:

  • React.memo(): This prevents function components from re-rendering unnecessarily
  • PureComponent: This prevents unnecessary re-rendering of class components

Both of these methods rely on propsa shallow comparison of what is passed to the component, and if  props it hasn't changed, the component won't re-render. While both tools are very useful, shallow comparisons come with an additional performance penalty, so both methods can negatively impact performance if used incorrectly.

By using  the React Profiler , performance can be measured before and after using these methods, ensuring that performance is actually improved by making a given change.

29. What is a pure function?

A pure function is one that has no dependencies and does not modify the state of variables outside its scope. Essentially, pure functions always return the same result given the same arguments.

30. How React   works when invokedsetStaterender

  1. Virtual DOM rendering: When renderthe method is called, it returns a new component's virtual DOM structure. When called setState(), it will be called again, because it always returns renderby default , so React is not optimized by default.shouldComponentUpdatetrue
  2. Native DOM rendering: React only modifies the real DOM nodes in the virtual DOM, and the number of modifications is very small - this is a great React feature, which optimizes the changes of the real DOM and makes React faster.

31. How to avoid rebinding instance in React ?

1. Define the event handler as an inline arrow function

class SubmitButton extends React.Component {

  constructor(props) {

    super(props);

    this.state = {

      isFormSubmitted: false

    };

  }

 

  render() {

    return (

      <button onClick={() => {

        this.setState({ isFormSubmitted: true });

      }}>Submit</button>

    )

  }

}

2. Use arrow functions to define methods:

class SubmitButton extends React.Component {

  state = {

    isFormSubmitted: false

  }

 

  handleSubmit = () => {

    this.setState({

      isFormSubmitted: true

    });

  }

 

  render() {

    return (

      <button onClick={this.handleSubmit}>Submit</button>

    )

  }

}

3. Use function components with Hooks

const SubmitButton = () => {

  const [isFormSubmitted, setIsFormSubmitted] = useState(false);

 

  return (

    <button onClick={() => {

        setIsFormSubmitted(true);

    }}>Submit</button>

  )

};

32. Distinguish between Real DOM and Virtual DOM ?

Real DOM Virtual DOM
1. Updates are slow. 1. Update faster.
2. HTML can be updated directly. 2. Cannot update HTML directly.
3. If the element is updated, a new DOM is created. 3. If the element is updated, update the JSX.
4. DOM operations are expensive. 4. DOM manipulation is very simple.
5. More memory is consumed. 5. Very little memory consumption.

 33.  What is React?

  • React is a front-end JavaScript library developed by Facebook in 2011.
  • It follows a component-based approach that helps in building reusable UI components.
  • It is used to develop complex and interactive web and mobile UIs.
  • Although it was only open-sourced in 2015, it has a large community of support

34. What are the characteristics of React?

The main functions of React are as follows:

  1. It uses virtual DOM  instead of real DOM.
  2. It can do server side rendering .
  3. It follows one-way data flow or data binding.

35.  List some of the main advantages of React

  1. It improves the performance of the application
  2. Can be easily used on client and server side
  3. Great code readability thanks to JSX
  4. React easily integrates with other frameworks like Meteor, Angular
  5. With React, writing UI test cases becomes very easy

36.  What are the limitations of React?

  1. React is just a library, not a complete framework
  2. Its library is huge and takes time to understand
  3. May be difficult for novice programmers to understand
  4. Coding becomes complicated as it uses inline templates and JSX

37.  Why can't browsers read JSX?

 Browsers can only handle JavaScript objects, they cannot read JSX inside regular JavaScript objects. So in order for the browser to read JSX, first, you need to use a JSX converter like Babel to convert the JSX file into a JavaScript object, and then pass it to the browser

38. How does React's ES6 syntax differ from ES5?

1. require and import

2.export and exports

3.component 和 function

4.props

5.state

39.  How is React different from Angular?

theme React Angular
1. Architecture Only View in MVC Complete MVC
2. Rendering Can do server-side rendering client rendering
3. DOM Use virtual DOM Use real DOM
4. Data Binding one-way data binding two-way data binding
5. Debugging compile-time debugging runtime debugging
6. Author Facebook Google

40.  How do you understand the phrase "In React, everything is a component"

Components are the building blocks of a React app's UI. These components divide the entire UI into small independent and reusable parts. Each component is independent of each other without affecting the rest of the UI.

41. How to explain the purpose of render() in React

Every React component is mandatory to have a  render() . It returns a React element that is a representation of a native DOM component. If multiple HTML elements need to be rendered, they must be grouped within a single enclosing tag, eg  <form>, <group>, <p> etc. This function must be pure, i.e. must return the same result each time it is called

42. What are props?

Props is shorthand for properties in React. They are read-only components and must remain pure, i.e. immutable. They are always passed from parent to child components throughout the application. Child components should never send props back to the parent. This helps maintain a unidirectional data flow and is often used to render dynamically generated data

43.  What is state in React? How is it used?

State is the core of React components, the source of data, and must be as simple as possible. Basically state is an object that determines the rendering and behavior of a component. Unlike props, they are mutable and create dynamic and interactive components. this.state() They can be accessed via 

44. Distinguish between state and props

condition State Props
1. Receive the initial value from the parent component Yes Yes
2. The parent component can change the value No Yes
3. Set the default value in the component Yes Yes
4. Changes inside the component Yes No
5. Set the initial value of the child component Yes Yes
6. Change inside the child component No Yes

45.  How to update the state of a component?

 The state of the component can be  this.setState()updated with .

46.  ​​What are arrow functions in React? how to use?

 Arrow functions ( => ) are a short syntax for writing function expressions. These functions allow the component's context to be properly bound, since automatic binding is not available by default in ES6. Arrow functions are very useful when working with higher order functions

47.  Distinguish between stateful and stateless components

stateful components stateless components
1. Store information about component state changes in memory 1. Calculate the internal state of the component
2. The right to change state 2. No right to change state
3. Include past, present, and possible future state changes 3. Does not include past, present and future possible state changes
4. Accept notifications of state-changing requirements for stateless components, and send props to them. 4. Receive props from stateful components and treat them as callback functions.

 48.  What are events in React?

In React, events are triggered reactions to specific actions such as mouse hover, mouse click, key press, etc. Handling these events is similar to handling events on DOM elements. But there are some syntax differences like:

  1. Use camelCase for event names instead of just lowercase.
  2. Events are passed as functions rather than strings.

Event parameters contain a set of event-specific properties. Each event type contains its own properties and behavior, which are only accessible through its event handlers

49. What are synthetic events in React?

Synthetic events are objects that act as cross-browser wrappers around browser-native events. They combine the behavior of different browsers into one API. This is done to ensure that events display consistent properties across browsers.

50. What is the importance of key in React?

A key is used to identify a unique Virtual DOM element and its corresponding data that drives the UI. They help React optimize rendering by recycling all elements currently in the DOM. These keys must be unique numbers or strings, React just reorders the elements instead of re-rendering them. This can improve the performance of the application

51. What is Redux ?

Redux is one of the hottest front-end development libraries today. It is a predictable state container for JavaScript programs, used for state management of the entire application. Apps developed with Redux are easy to test, can run in different environments, and show consistent behavior

 52. What are the three principles that Redux follows?

  1. Single source of truth: The state of the entire application is stored in an object/state tree in a single store. A single state tree makes it easier to track changes over time and debug or inspect applications.
  2. The state is read-only: the only way to change the state is to trigger an action. Actions are plain JS objects that describe changes. Just as state is a minimal representation of data, the operation is a minimal representation of a change to data.
  3. Changes using pure functions: In order to specify how the state tree is transformed by operations, you need pure functions. Pure functions are those whose return value depends only on the values ​​of their arguments.

53.  What do you understand by "single source of truth"?

 Redux uses a "Store" to store the entire state of the program in one place. So the state of all components is stored in the Store, and they receive updates from the Store itself. A single state tree makes it easier to track changes over time and debug or inspect programs

54. List the components of Redux

  1. Action  - This is an object describing what happened.
  2. Reducer  - This is where it is determined how the state will change.
  3. Store  - The state/object tree of the entire program is kept in the Store.
  4. View  - Only display the data provided by the Store.

55.  How does data flow through Redux?

56.  How to define Action in Redux

Actions in React must have a type attribute that indicates the type of ACTION being executed. They must be defined as string constants, and more properties can also be added to them. In Redux, actions are created by functions called Action Creators

57. Explain the role of Reducer

Reducers are pure functions that specify how the state of the application changes in response to ACTIONs. Reducers work by taking a previous state and action, then it returns a new state. It determines what kind of update needs to be performed based on the type of operation, and returns the new value. If there is no need to complete the task, it will return to the original state

58. What is the significance of Store in Redux

A Store is a JavaScript object that holds the state of the program and provides methods to access the state, dispatch operations, and register listeners. The entire state/object tree of the application is kept in a single store. Therefore, Redux is very simple and predictable. We can pass middleware to the store to process data and record various operations that change the state of the store. All operations return a new state via reducers.

59. What are the advantages of Redux?

The advantages of Redux are as follows:

  • Predictability of results -  Since there is always one source of truth, the store, there is no question of how to synchronize the current state with actions and other parts of the app.
  • Maintainability -  Code becomes easier to maintain, with predictable results and strict structure.
  • Server side rendering -  you just pass the store created on the server to the client. This is useful for initial rendering and optimizes app performance for a better user experience.
  • Developer Tools -  From actions to state changes, developers can track everything happening in the app in real time.
  • Community and Ecosystem -  There is a huge community behind Redux which makes it even more fascinating. A large community of talented individuals has contributed to library improvements and developed various applications.
  • Ease of testing -  Redux's code is mostly small, pure and self-contained functions. This makes the code testable and self-contained.
  • Organization -  Redux explains exactly how the code is organized, which makes the code more consistent and simple when used by the team

60. What is React Routing

 React Routing is a powerful routing library built on top of React which helps to add new screens and flows to the application. This keeps the URL in sync with the data displayed on the web page. It is responsible for maintaining a standardized structure and behavior, and is used to develop single-page web applications. React routing has a simple API

61.  Why is the switch keyword used in React Router v4 

 Although  <p> used to encapsulate multiple routes in a Router, the "switch" keyword can be used when you want to only display a single route to be rendered among multiple defined routes. When used, <switch> tags match defined URLs with defined routes in order. After finding the first match, it renders the specified path. thereby bypassing other routes

62.   Why do you need routing in React?

Router is used to define multiple routes, when a user defines a specific URL, if this URL matches the path of any "routes" defined within Router, the user will be redirected to that specific route. So basically we need to add a Router library to our application that allows creating multiple routes, each of which will provide us with a unique view

63. List the advantages of React Router.

  1. Just like React is based on components, in React Router v4 the API is  'All About Components' . A Router can be visualized as a single root component ( ), where we wrap <BrowserRouter>specific sub-routes ( ).<route>
  2. No need to manually set history values: In React Router v4, all we had to do was wrap routes in  <BrowserRouter> components.
  3. The packages are separated: there are three packages for Web, Native and Core. This makes our application more compact. Easy to switch based on similar coding style

64. How is React Router different from regular routing?

theme regular routing React Routing
participating pages Each view corresponds to a new file only involves a single HTML page
URL changes An HTTP request is sent to the server and the corresponding HTML page is received Only change history properties
to experience The user actually switches between different pages in each view Users think they are switching between different pages

65. Commonly used hooks

 useState: Define the data of the state, the parameter is the initialized data, and the return value is two values ​​1. Initialization value, 2. Modification method

useEffect: side effect function, as the name suggests, side effects only occur after use

  1. Use it as a life cycle: If the second parameter is not written, it will be triggered when the page is updated, compoentDidMount compoentDidUpdate

  2. If the second parameter is an empty array, it will only be executed once, compoentDidMount

  3. Some variables in the array are used as listeners to monitor data changes,

  4. useEffect is a side effect function, which is triggered after the component update is completed

  5. If we return a function from useEffect, trigger when the component is destroyed

useMemo: used to calculate data, return a result, and monitor data changes. The second parameter is the monitored data, which is cacheable

Compared with useMemo and useEffect, useMemo triggers the life cycle when the component is updated

How does useMemo optimize performance?

When the parent component communicates with the child component, the data in the parent component changes. Updating the parent component will cause the child component to be updated and rendered, but if the modified data has nothing to do with the child component, updating the child component will cause unnecessary DOM for the child component Rendering is more performance consuming. At this time, we can use useMemo or memo as component cache to reduce unnecessary DOM rendering of subcomponents

useCallback: When the parent component passes a function to the child component, the change of the parent component will cause the re-call of the function to generate a new scope, so it will still cause the update rendering of the child component. At this time, we can use useCallback to cache the component

useRef: Equivalent to the use of createRef, creating component attribute information

useContext: It is equivalent to obtaining the content information of the context state number in the function component

useReducer: useReducer is used to make up for the deficiency of useState. It can manage the data in a centralized manner and process the logical information of the data separately.

66. How to use ref in react?

1. You can write a string directly, but it only applies to class components

2. createRef and useRef to define ref variable, ref.current to get data

3. You can use the arrow function method to define a variable in advance, and the formal parameter of the arrow function is the current object 

const App = ()=>{
  let h = useRef();

  let inp = null;//定义一个空变量

  const setVal = ()=>{
    console.log(inp.value);
  }
  return (
    <div>
      <h3 ref={h}>ceshi</h3>
      <button onClick={()=>console.log(h.current)}>获取</button>

      <hr />
      <input placeholder="输入内容" ref={(el)=>{ inp = el; }} onChange={setVal}/>
    </div>
  )
}

The ref attribute cannot be directly bound to the function subcomponent. The function component does not have this object, and the object content of the function subcomponent cannot be obtained. Finally, the function component forwardRef high-order component component can pass the ref attribute to the function subcomponent through the parameter parameter Internally, the operation of forwarding the ref attribute

Guess you like

Origin blog.csdn.net/qq_60976312/article/details/125783396