Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React createRef() vs callback refs. Is there any advantage of using one over the other?

Tags:

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

like image 677
Vishwas Avatar asked Dec 05 '18 03:12

Vishwas


People also ask

Is it true that refs are created using React createRef () and attached to React elements via the ref attribute?

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.

Why ref is not recommended in React?

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.

What is the use of createRef in React?

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.

Is React createRef the same as useRef?

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.


1 Answers

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}             />)         );     } } 
like image 127
Tai Ly Avatar answered Sep 21 '22 07:09

Tai Ly