Using useImperativeHandle and useRef Hooks in React
Have you ever come across a situation where you need to interact with a child component from its parent? Or maybe you need to access the underlying DOM element of a component?
In React, we can achieve this using the useImperativeHandle
and useRef
Hooks. These Hooks provide a way to define custom methods and access the underlying DOM element of a component.
useRef Hook
The useRef
Hook in React allows us to create a mutable reference that persists across re-renders. It returns a mutable object with a .current
property, which can hold a value. Unlike useState
, updating the value of the reference does not trigger a re-render.
Here’s an example of how to use the useRef
Hook:
import React, { useRef } from 'react';
function MyComponent() {
const inputRef = useRef();
const focusInput = () => {
inputRef.current.focus();
};
return (
<div>
<input ref={inputRef} />
<button onClick={focusInput}>Focus Input</button>
</div>
);
}
In this example, we create a reference using the useRef
Hook and assign it to the input element. We also define a focusInput
function that focuses the input element when the button is clicked.
useImperativeHandle Hook
The useImperativeHandle
Hook allows us to customize the instance value that is exposed to the parent component when using ref
. It takes a ref
and a factory function as arguments. The factory function should return an object with the methods or values that we want to expose.
Here’s an example of how to use the useImperativeHandle
Hook:
import React, { useRef, useImperativeHandle } from 'react';
const ChildComponent = React.forwardRef((props, ref) => {
const hiddenInputRef = useRef();
useImperativeHandle(ref, () => ({
focusHiddenInput: () => {
hiddenInputRef.current.focus();
}
}));
return (
<input type="text" style={{ display: "none" }} ref={hiddenInputRef} />
);
});
function ParentComponent() {
const childRef = useRef();
const focusHiddenInput = () => {
childRef.current.focusHiddenInput();
};
return (
<div>
<button onClick={focusHiddenInput}>Focus Hidden Input</button>
<ChildComponent ref={childRef} />
</div>
);
}
In this example, we create a child component using the useImperativeHandle
Hook. We define a focusHiddenInput
method and expose it to the parent component using the ref
. The parent component can then call this method to focus the hidden input element.
Conclusion
The useImperativeHandle
and useRef
Hooks are powerful tools in React for interacting with child components and accessing the underlying DOM. By using these Hooks, we can enhance the functionality and performance of our React components.
I hope this article has provided you with a good understanding of how to use the useImperativeHandle
and useRef
Hooks in React. Happy coding!