From the course: Build Modern Web Apps with React, Hooks, State Management, and APIs Using Vite or Next.js

Unlock this course with a free trial

Join today to access over 25,200 courses taught by industry experts.

useImperative example and uses

useImperative example and uses

Hello and welcome back. Let's see how the exposing methods to parent work with the help of useImperativeHandleHook. We have to use it inside a component that is going to receive a reference from its parent via the forward ref. So let's take a look at the parent component first, which is defined below down here. In the parent component, we have declared a input reference using the useRef hook. And in the JSX, we are calling the custom input component, which is a child component. And we are passing on the reference to inputRef. After that, we have a button, which is calling an onClick event on the input reference. And the first function is focus input and the other function is clear input. Now let's get to the child component itself. We have defined a child component here which is named custom input and we define that component using the forward ref function. We can import it from react. This is necessary, just like the previous example of the hook we did. So we have to call it using…

Contents