I see that React.forwardRef seems to be the sanctioned way of passing a ref to a child functional component, from the react docs:
const FancyButton = React.forwardRef((props, ref) => (
<button ref={ref} className="FancyButton">
{props.children}
</button>
));
// You can now get a ref directly to the DOM button:
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;
However, what is the advantage of doing this over simply passing a custom prop?:
const FancyButton = ({ innerRef }) => (
<button ref={innerRef} className="FancyButton">
{props.children}
</button>
));
const ref = React.createRef();
<FancyButton innerRef={ref}>Click me!</FancyButton>;
The only advantage I can think of is maybe having a consistent api for refs, but is there any other advantage? Does passing a custom prop affect diffing when it comes to rendering and cause additional renders, surely not as the ref is stored as mutable state in the current
field?
Say for example you wanted to pass multiple refs (which tbh, might indicate code smell, but still), then the only solution I can see would be to use customRef props.
I guess my question is what is the value of using forwardRef
over a custom prop?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…