I have started working on React recently and understood how refs can be used to get hold of a DOM node. In the React docs, they mention the two approaches of creating Refs. Can you please let me know in what situation a callback ref is better than createRef()? I find createRef to be simpler. Although the docs say "callback refs give you more fine grain control" I can't understand in what way. Thank you
Refs are created using React. createRef() and attached to React elements via the ref attribute. Refs are commonly assigned to an instance property when a component is constructed so they can be referenced throughout the component.
It is a general rule of thumb to avoid using refs unless you absolutely have to. The official React documentation outlined only three possible use cases where refs are entirely considered useful for lack of better alternatives: Managing focus, text selection, or media playback. Triggering imperative animations.
This method is used to access any DOM element in a component and it returns a mutable ref object which will be persisted as long as the component is placed in the DOM. If we pass a ref object to any DOM element, then the. current property to the corresponding DOM node elements will be added whenever the node changes.
useRef: The useRef is a hook that uses the same ref throughout. It saves its value between re-renders in a functional component and doesn't create a new instance of the ref for every re-render. It persists the existing ref between re-renders. createRef: The createRef is a function that creates a new ref every time.
Besides what jmargolisvt said, one thing I found callback is very interesting that I can set multiple refs in an array so that I can control it better. Like this:
class A extends React.Component { constructor(props) { super(props); this.inputs = []; } render() { return [0, 1, 2, 3].map((key, index) => ( <Input key={key} ref={input => this.inputs[index] = input} />) ); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With