React Refs Vs Forward Ref? See Example

Both Refs and Forward Refs are used to access DOM elements, but they have different use cases:

  • Refs: Used inside a component to access its own DOM element.
  • Forward Ref: Allows a parent component to pass a ref to a child component.

Ref Example

import React, { useRef } from "react";

function Input() {
  const inputRef = useRef();

  return (
    <div>
      <input ref={inputRef} />
      <button onClick={() => inputRef.current.focus()}>Focus Input</button>
    </div>
  );
}

✅ Access DOM element within the same component.


Forward Ref Example

import React, { useRef } from "react";

const Input = React.forwardRef((props, ref) => <input ref={ref} />);

function App() {
  const inputRef = useRef();

  return (
    <div>
      <Input ref={inputRef} />
      <button onClick={() => inputRef.current.focus()}>Focus Input</button>
    </div>
  );
}

✅ Parent can access child input element using Forward Ref.


Key Differences

FeatureRefsForward Ref
UsageAccess component’s own DOMPass ref from parent to child
ScopeInside the same componentAcross components
PurposeDirect DOM accessParent control of child DOM
Component TypeAny componentFunctional child components

Conclusion

Use Refs for internal DOM access, and Forward Ref when the parent needs to interact with the child’s DOM element.


Citations

https://savanka.com/category/learn/react/
https://www.w3schools.com/REACT/DEFAULT.ASP

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *