React useImperativeHandle
Created By: chatGPT
The
useImperativeHandle
hook in React is used in conjunction with forwardRef
to customize the instance value that is exposed to parent components when using refs. This can be useful when you want to expose specific methods or properties of a child component to its parent, instead of the entire component instance.import React, { useImperativeHandle, forwardRef, useRef } from 'react';
const CustomInput = forwardRef((props, ref) => {
const inputRef = useRef();
// useImperativeHandle allows us to customize the exposed instance
useImperativeHandle(ref, () => ({
focus: () => {
inputRef.current.focus();
},
getValue: () => {
return inputRef.current.value;
}
}));
return <input ref={inputRef} />;
});
const ParentComponent = () => {
const inputRef = useRef();
const handleFocus = () => {
// Call the focus method from the child component
inputRef.current.focus();
};
const handleGetValue = () => {
// Call the getValue method from the child component
alert(inputRef.current.getValue());
};
return (
<div>
<CustomInput ref={inputRef} />
<button onClick={handleFocus}>Focus Input</button>
<button onClick={handleGetValue}>Get Input Value</button>
</div>
);
};
In the example above, we have a
CustomInput
component that uses forwardRef
to pass its internal ref to the parent. Inside useImperativeHandle
, we define the functions focus
and getValue
, controlling what gets exposed to the parent. The ParentComponent
utilizes these functions to interact with the input within the child component.export default ParentComponent;