Current section: Imperative Handles 36 exercises
lesson

Intro to Imperative Handles

Loading lesson

Transcript

00:00 I love React's declarative model just as much as anybody else. But sometimes you need to have some imperative API as an escape hatch for performing imperative things. And what I mean by that is telling the computer what to do specifically. Like, we need to focus this input, for example.

00:19 And we can do this using imperative handles. So here's an example. We've got this MyInput component, and it accepts a prop called ref, which is a ref object leveraging the input API that we created.

00:34 So we're going to make a focus input function on this ref object. So we add that right here, and when it's called, it's going to focus. Now, this is actually not the way that you use this hook. You'll notice we don't have useImperativeHandle in here at all. And while this will technically work, it's not optimal for various reasons.

00:54 React is actually going to be rendering your component sometimes without ending up creating React elements or using those React elements and stuff. And so you could end up in a situation where this doesn't work out very well, which is why we have the hook. But it technically does work most of the time.

01:12 And so by adding or setting the current property to this object, then a user of our component can create a ref, pass that to the input component,

01:27 and then at any time they can imperatively say, okay, you component, I need you to do this thing. This is not something you actually do very often, but I absolutely have done it before. In fact, the workshop app that you're using right now uses useImperativeHandle,

01:46 and literally today during my office hours, somebody asked me a question and the answer was useImperativeHandle. So it is something that you use occasionally, but not really all that often. So useImperativeHandle is a little bit more specific in that you can provide the ref object itself,

02:04 and then as a second argument, you provide a function that returns what you want assigned to the ref. This is a lot safer with all of the interesting things that React has going on behind the scenes. And then, of course, that should look familiar, dependency array right there.

02:19 So your job is, well, I'll explain your job here in a second. That is useImperativeHandle accepts a ref and a function to assign to the current property of that ref, and then users of your component will be able to call methods within your component imperatively.

02:38 Good escape hatch. Not something you want to do all the time, but yeah, pretty useful sometimes.