If you already have a subscription, you can sign in.
Enjoy free content straight from your inbox 💌
00:00
In web development, there are certain things that we can only do when we have direct access to the underlying dorm element. This poses a problem when we are working with React because most commonly we are working with virtual dorm. But fortunately, react has a neat solution for this problem in the form of the use Rev hook. In this lesson, we will look at how the use ref hook works, how it is different from EU state, and some pretty neat tricks that we can do with refs. So let's go to demonstrate the need for Direct Tom Access. Consider a simple input whose value we will throw with EU state, and then we will displace some message
00:35
to the user based on the value that the user provides, whether the value is valid or not. We will create a simple function that will first check if the value is provided and if it is not, we are going to say that it is invalid. The user should provide a value, otherwise we will show a successful message for the rendering of our component. We will create an input wired to value and set value, create a simple paragraph to display the message and a simple button wired to own submit. And this is a very simple and effective ui. The user can provide a value, choose to submit,
01:08
at which point we do the validation. And if the user doesn't provide a value, of course we will display a message that please enter a value. Now at this point, because the user click the submit button, the focus is still going to be on the submit button. So it's not very easy for the user to fix the error that they just got. They have to manually go and then focus the input that has an error and then fix that value. What would be great, and this is conventional behavior in a lot of web forms, is that we automatically focus the location where the error is so that the user can easily fix that error. Now, in order to do this, we would need access
01:43
to the underlying dorm HTML input element that React will render for this V dorm node. Fortunately, we can get that access quite easily with the use ref hook. This hook is available from the React module, just like you state. And then we invoke it from the root of the component where we want the DOM axis. We should provide an initial value for the reference and it's conventional to set it to null for dom elements. And then because we are using TypeScript, we can also provide a type parameter for the type of the element that we want to store.
02:15
In our particular case, we want to store an HTMO input element. This gives us back a mutable ref object and the great thing about it is that every single time the component will read render reactable returners the exact same object so that we can read and mutate the same object reliably. Now all the DOM elements within React actually take a ref prop and the value that you provide is this mutable ref object and the element component will automatically set the current property of this ref object once it gets rendered. This means that once the component has been rendered,
02:50
we can get access to the dorm element with Rev current. And this allows us to use the input rev current to invoke The focus method of the HTML input element. Now, because the current member is going to be initially null when the component hasn't been rendered, we just have to make sure that we use optional chaining to safely invoke the focus method. With this simple focus call in place when the user clicks the submit button without providing a value, not only do we notify the user, we also take them to the input so they can easily start typing and providing a value to fix that error.
03:24
And that is the basics of the use rev hook. We invoke it just like any other hook within our component to get immutable object, give this rev object, do some dorm element, and then use this object's current property to access that Tom element. An obvious question that you should have at this point is that if ref is just some state that is associated with the component, how is it different from you state and when should you use R instead of you state? The difference between the two hooks is actually quite simple and yet quite critical to demonstrate that. Consider a simple UI where we have a value wide
04:00
to an input element and our objective is to keep track of every single time the component gets rendered and display the number of renderings on screen. Let's keep track of this count with a U State variable. Now we already know that we get notified every single time the component gets rendered with use effect. So within that we increment the count by one. And finally within the UI we display the rendered count within a simple tiv. Now this feels like wallet code to count the number of renderings. However, within the UI you can see that we have somehow an infinite loop.
04:34
And the reason for this constant rear-ending might be already obvious to some of you whenever we call the set function of EU state that causes a rear-ender that causes a new call to use effect that causes a new call to the set function. And that's our infinite loop. And this is the key difference between you state and the mutable ref object. Unlike the state set function, changing the mutable ref current does not cause a re-render. So if you want to track a value without causing a re-render, we need to use ref.
05:08
We store the optimistic value of the renders as a ref, which we initialize to one, and then every single time the component has been rendered, we increment the value by one more. And then within the UI we display the ref objects current member. So the first time the component gets rendered, we will display the ref object's current value, which of course is one, and every single time the component will render, for example, us changing the value of the input. The rendered count is being maintained by the ref without causing additional renders error score.
05:41
Ref is just some state that you can associate with the component that you should be able to set without causing a re-render. And this can be used for simple performance optimizations by storing any value that is not directly used in the rendering of the component. As another example, Consider a simple timer replication that displayed the number of seconds that have elapsed. Since we have started a timer, the seconds which are going to get rendered to the UI are stored with U State. However, the underlying set interval results does not need to be rendered to the ui.
06:14
So we can store that with a simple use ref. We create a simple utility function that will start the interval, and here we modifies the refs current value with the result of set interval. And then we create a utility for clearing the interval where we would read the ref's current value. And if it exists, we would use the clear interval function to get rid of the timer. Finally, as good citizens, we would make sure that clear interval gets called when the component gets unmounted with use effect. The UI of our component is going to be pretty simple.
06:46
We simply rendered to button components, one wired to start interval, one wired two clear interval, followed by the current seconds displayed in a simple div. And the UI works exactly how you would expect. We can start the timer and then we see the time incrementing, and at any point that we want, we can stop the timer by calling clear interval at which point the timer will stop. And this example I demonstrates the usage of some state where we want the UI to re-render, and then some state which is the interval refs where we do not want the component
07:19
to re-render when we set them and often overlook feature of the ref prop with native dorm elements is that in addition to simple mut objects, they also support callback functions. So let's demonstrate these two behaviors of the ref prop with some simple instrumentation. Let's use a simple input element to demonstrate these two behaviors of the ref prop. The first behavior, of course, is passing in a mutable object and we can actually create our own object, which has a member called current. And whenever someone tries to set the current, you will actually log whatever value gets passed in.
07:52
And this is pretty much what the result of use ref is. It is an object that has a current member, and when you give it to something native, for example, an input on rendering the native element, the component will try to set the current property for that object. And indeed, this is proven by the log that we are putting for our custom object. Now, in addition to passing a multiple object as the ref, you can actually pass in a callback function as well, and when the component will render, it'll pass in the rendered native dorm element to the callback.
08:25
This callback version of the RevPro is useful because it allows you to get notified when a child's dorm element gets rendered by react. I'll wrap things up there. As always, thank you for joining me and I'll see you in the next one.