In React, the useImperativeHandle hook allows you to customize the instance value that is exposed when a parent component calls ref on a child component. This is often used when you want to provide a way for the parent component to directly interact with specific methods or properties of the child component.
useRef is a hook used to create a mutable reference that can be used to hold a reference to a DOM element or any other value that you want to persist across renders.
Here’s how you can use useRef with useImperativeHandle in a child component:
import React, { useRef, useImperativeHandle, forwardRef } from 'react';
// Child component
const ChildComponent = forwardRef((props, ref) => {
// Create a ref to hold the value you want to expose
const internalValueRef = useRef();
// Define methods or properties that you want to expose
const doSomething = () => {
// ... do something
};
// Use useImperativeHandle to expose specific functionality to the parent
useImperativeHandle(ref, () => ({
// The keys defined here are what the parent can access on the ref
doSomething,
internalValue: internalValueRef.current,
}));
// ... rest of your component logic
return <div>Child Component</div>;
});
// Parent component
const ParentComponent = () => {
// Create a ref to hold the child component instance
const childRef = useRef();
const handleClick = () => {
// Now you can call methods or access properties of the child component
if (childRef.current) {
childRef.current.doSomething();
console.log(childRef.current.internalValue);
}
};
return (
<div>
<ChildComponent ref={childRef} />
<button onClick={handleClick}>Call Child Method</button>
</div>
);
};
export default ParentComponent;
In this example, the ChildComponent uses useImperativeHandle to expose the doSomething method and the internalValue property to the parent component through the ref. The ParentComponent creates a childRef using the useRef hook and passes it to the ChildComponent. This allows the parent component to call the exposed method and access the exposed property of the child component.
Real Example
Look input.js and login.js
Credits: https://www.udemy.com/course/react-the-complete-guide-incl-redux/