‫So, with the topic of useState now behind us,
‫let's turn our focus on something called refs.
‫And so, in this lecture, let's manually select a dom element
‫so that you see why we actually need refs in React.
‫So, as an experiment,
‫let's try to automatically give this input element, here,
‫focus each time that the Search component mounts.
‫So, basically, each time the application mounts,
‫we will automatically focus on this input field.
‫Okay.
‫And, in order to do that,
‫we actually need to select this element.
‫And so let's try to do that
‫with the tools that we already have.
‫So we come here into our Search component,
‫which is where that input field is located.
‫And so, then, we can basically use a useEffect
‫and then manually select this dom element right here.
‫So let's try that out.
‫And then let's execute this effect
‫as soon as this component mounts.
‫So let's create some element
‫by simply doing document.querySelector,
‫and then we can just use the className
‫that is already here on the element,
‫so .search.
‫Okay, just to see if this works,
‫let's log this to the console.
‫And you see that, indeed, there is our input field.
‫And so now what we can do is to just say el,
‫so just this element,
‫and then call the focus method on that.
‫And so this is just some straightforward,
‫typical dom manipulation.
‫Okay.
‫And so now, if we load the application,
‫and so you see, as the application first loaded,
‫this input field automatically got focused,
‫so our code here is basically doing its job.
‫However, as we learned at the very beginning,
‫React is all about being declarative.
‫And so manually selecting a dom element like this
‫is not really the React way of doing things.
‫So it's not in line with the rest of our React code.
‫So, in React, we really don't want
‫to manually add event listeners, like this,
‫and also having to add classes or IDs
‫just for the purpose of selecting is not really nice.
‫And, again, not really the React way of doing things.
‫So here we already had the className, of course,
‫but if we didn't,
‫then we would have to now add that className or ID here
‫to then use it in the effect to select the element.
‫Also, if for some reason we would need some dependency here,
‫for example,
‫if this code should rerun each time the query changes,
‫then that would mean
‫that we would select the element here over and over again,
‫which is also not ideal.
‫Okay, and so, to solve all these problems
‫and to make the action
‫of selecting an elements more declarative,
‫such as everything else in React,
‫we need the concept of refs.
‫And so that's what we're going to learn about
‫in the next video.