Member-only story
useRef vs forwardRef
2 min readJun 19, 2023
Refs in react can be used for DOM manipulations — for example, to focus a node, scroll to it, or measure its size and position
useRef hook to focus the input text box
import React, { useRef } from 'react';
export default function App() {
const textInputRef = useRef(null);
function focusTextBox() {
textInputRef.current.focus();
//here current will refer the input element,
//like selecting the element by any element selectors
//(ex: document.querySelector('input'))
//any dom manipulations can be done
}
return (
<div>
<input ref={textInputRef} />
<button onClick={focusTextBox}> Focus the text box</button>
</div>
);
}
Use of forwardRef
By default, using ref, the DOM manipulations of other components, even if it is own child components is prohibited.
export default function App() {
const textInputRef = useRef(null);
function focusTextBox() {
textInputRef.current.focus();
}
return (
<div>
<Child ref={textInputRef} />
<button onClick={focusTextBox}> Focus the text box</button>
</div>
);
}
const Child = (props) => {
return <input ref={props.textInputRef} />;
};
Now we have moved the input text box in the child component and referring with the ref of parent.
So that is when forwardRef api comes into picture (it is not hook -remember hooks should start with use)
import React, { useRef…