The useImperativeHandle Hook
It is a React hook that allows you to customize the instance value that is exposed when using ‘ref‘ with ‘React.forwardRef‘. It’s particularly useful when you’re working with third-party libraries or integrating with imperative APIs and need more control over the exposed methods or properties of a component.
Syntax:
useImperativeHandle(ref, () => {
// Return an object representing the public API of the component
return {
exposedFunction1,
exposedFunction2,
};
}, [dependencies]);
Example: Below is an example of useImperativeHandle hook.
import React, {
useRef,
useImperativeHandle,
forwardRef
} from 'react';
// Child component that forwards a ref
const ChildComponent = forwardRef((props, ref) => {
const inputRef = useRef(null);
// Expose custom imperative methods
useImperativeHandle(ref, () => ({
focus: () => {
inputRef.current.focus();
},
reset: () => {
inputRef.current.value = '';
}
}));
return <input ref={inputRef} />;
});
// Parent component using the child component
function Gfgarticle() {
const childRef = useRef(null);
const handleFocusClick = () => {
childRef.current.focus();
};
const handleResetClick = () => {
childRef.current.reset();
};
return (
<div>
<h1>This is useImperativeHandle Hook</h1>
<ChildComponent ref={childRef} /><br></br><br></br>
<button onClick={handleFocusClick}>
Focus Input
</button>
<button onClick={handleResetClick}>
Reset Input
</button>
</div>
);
}
export default Gfgarticle;
Output:
Additional Built-in Hooks in React
Hooks are functions that allow you to “hook” into the state of a component and provide additional features to ensure the lifespan of functional components. These are available in React versions 16.8.0 and higher. however, we previously used to describe them using classes.
We will discuss the various Additional Built-in Hooks:
Table of Content
- The useReducer hook
- The useRef hook
- The useCallback Hook
- The useMemo Hook
- The useLayoutEffect Hook
- The useImperativeHandle Hook
- The useDebugValue Hook
- Conclusion