What is the use of refs ?
What is the use of refs ?
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:
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].
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].
Triggering Imperative Animations: Refs can be used to control animations directly by accessing DOM nodes and manipulating their properties[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].
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].
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
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào