useImperativeHandle Vs useRef In React? Complete Example Guide

Both hooks deal with refs in React, but their purpose differs:

  • useRef: Provides a mutable object to access DOM elements or store values.
  • useImperativeHandle: Customizes the instance value exposed to parent when using forwardRef.

useRef 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 directly within the component.


useImperativeHandle Example

import React, { useRef, forwardRef, useImperativeHandle } from "react";

const Child = forwardRef((props, ref) => {
  const inputRef = useRef();

  useImperativeHandle(ref, () => ({
    focusInput: () => inputRef.current.focus()
  }));

  return <input ref={inputRef} type="text" />;
});

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

  return (
    <div>
      <Child ref={childRef} />
      <button onClick={() => childRef.current.focusInput()}>Focus Input</button>
    </div>
  );
}

✅ Parent can call custom method on child using useImperativeHandle.


Key Differences

FeatureuseRefuseImperativeHandle
PurposeAccess DOM or store valuesCustomize child instance ref
ScopeWithin componentAcross parent-child
Requires forwardRef?NoYes
Use CaseInput focus, timers, mutable refExpose custom child methods

Conclusion

Use useRef for direct DOM access, and useImperativeHandle to expose custom methods from child components.


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 *