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

What is the use of refs ?

Câu trả lời

In ReactJS, refs (short for references) are used to directly access and interact with DOM nodes or React component instances within the application. They serve as an "escape hatch" from React's typical data flow, providing a way to modify children outside of the usual declarative data flow. Here are the primary uses and characteristics of refs:

  1. Accessing DOM Elements: Refs provide a direct way to access DOM nodes. This is particularly useful for managing focus, text selection, or media playback, which might otherwise be cumbersome with React's declarative API alone[1][2][3].

  2. Integrating with Third-Party DOM Libraries: When using third-party libraries that interact with the DOM, refs make it possible to give these libraries access to DOM nodes created by React[1][2].

  3. Triggering Imperative Animations: Refs can be used to control animations directly by accessing DOM nodes and manipulating their properties[4].

  4. Avoiding Additional Renders: Unlike state updates, changes to refs (e.g., updating the .current property) do not trigger re-renders. This can be advantageous for optimizing performance when you need to manage mutable data without causing a new render[1][2][3].

  5. Storing Mutable Values: Refs can hold mutable values that you want to persist across renders but do not impact the rendering logic directly. This is useful for values like timers or manually managed counters[1][2][5].

How Refs Work

Refs are created using React.createRef() in class components or useRef() in functional components. A ref created with React.createRef() returns an object with a ...

entry

entry

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

senior

What is the second argument that can optionally be passed to setState and what is its purpose?

senior

When to use useCallback , useMemo and useEffect ?

expert

What is the order of useInsertionEffect , useEffect and useLayoutEffect hooks at component generation ?

Bình luận

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

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