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

When would you use useRef ?

Câu trả lời

The useRef hook in React is used in several scenarios where you need to maintain a mutable reference to a value or a DOM element across component renders without causing re-renders. Here are some specific situations when you might use useRef:

  1. Accessing DOM Elements: useRef is commonly used to directly access a DOM element in your component. For example, you might use it to focus an input element or to read the size or position of an element on the screen[1][2][3][4][5][6][7][8][9][10][11][12][13][14][15][16][17][18][19][20].

  2. Storing Mutable Values: If you need to keep track of a value that changes over time but does not impact the rendering of your component, useRef is a suitable choice. This is because changes to a ref's .current property do not trigger re-renders. This can be useful for values like timers, intervals, or any external mutable state[1][2][3][4][5][6][7][8][9][10][11][12][13][14][15][16][17][18][19][20].

  3. Preserving Values Between Renders: useRef can be used to hold onto data across renders if you want to prevent re-initialization of a variable on every render. This is particularly useful for preserving the previous state of a variable or the previous props a component received[1][2][3][4][5][6][7][8][9][10][11][12][13][14][15][16][17][18][19][20].

  4. Implementing Instance Variables: Refs can act like instance variables in class components. They can be used to store a mutable value that is tied to the lifecycle of a component but does not influence the view layer directly[1][2][3][4][5][6][7][8][9][10][11][12][13][14][15][16][17][18][19][20].

  5. Managing Focus, Text Selection, or Media Playback: useRef is useful for managing UI elements that require direct interaction, such as focusing inputs, selecting text, or controlling media playback (play, pause, etc.)[1][2][3][4][5][6][7][8][9][10][11][12][13][14][15][...

middle

middle

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

middle

What are Pure Components?

middle

How would you pass data from child to parent component in React?

junior

What are Controlled components in ReactJS?

Bình luận

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

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