Câu hỏi phỏng vấn Reactjs
Câu hỏi

What would be the common mistake of function being called every time the component renders?

Câu trả lời

The common mistake that leads to a function being called every time a component renders in React is when the function is invoked directly within the JSX, rather than being passed as a reference to an event handler. This typically happens when a developer includes parentheses after the function name within the JSX, which causes the function to execute during the rendering process.

For example, consider the following incorrect usage:

jsx Copy
<button onClick={this.activatePlaylist(playlist.playlist_id)}>Play</button>

In this case, activatePlaylist is being called immediately as the button element is rendered, rather than being called in response to the onClick event.

The correct approach is to pass a reference to the function, which can be done in several ways:

  1. Binding the function in the constructor and then passing the bound function:
jsx Copy
constructor(props) {
  super(props);
  this.activatePlaylist = this.activatePlaylist.bind(this);
}

// ...

<button onClick={() => this.activatePlaylist(playlist.playlist_id)}>Play</button>
  1. Using an arrow function in the render method to wrap the function call:
jsx Copy
<button onClick={() => this.activatePlaylist(playlist.playlist_id)}>Play</button>
  1. Binding the function directly in the JSX (not recommended due to potential performance issues):
jsx Copy
<button onClick={this.activatePlaylist.bind(this, playlist.playlist_id)}>Pla...
middle

middle

Gợi ý câu hỏi phỏng vấn

middle

What is the difference between ShadowDOM and VirtualDOM?

senior

How would you store non-state/instance variables in functional React components?

junior

How to create refs in React?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào