The useRef
hook allows us to leverage React refs within our function components. Refs can be assigned to DOM elements in order to allow us to manipulate them directly.
It is important, however, to note that this is somewhat of an anti-pattern in React as JavaScript frameworks usually handle updating the browser DOM after the virtual DOM has changed.
useRef
only takes one argument: its initial value. In the code snippet below, you can see how it is then assigned to an <input />
:
// Instantiate the ref
const inputRef = useRef(null);
// Assign `inputRef` to the <input /> element
<input ref={inputRef} type="search" />
Ryan Harris: [0:00] Inside of our SearchInput() component, let's define a ref. We'll call it const inputRef = useRef(), and we'll pass it at the default value of null. Now that we created this inputRef here, let's assign it to one of the DOM elements below.
[0:14] In this case, we're going to use the input here. We'll say ref = {inputRef}. In doing this, the inputRef's current field will point directly to this HTML input wlement. We can now use that to manipulate our input.
[0:29] Let's say we want to add autoFocus to our input. We'll need to add a useLayoutEffect here, useLayoutEffect. This is only going to change when the autoFocus prop changes. We'll need to make sure that's coming in from our pair component, autoFocus. What we'll do is if the autoFocus prop is true, we'll take the inputRef.current, and call focus().
[1:02] Then, we'll also setFocused, a local state here, to true, so that we get the right styles from this className down below.
[1:10] Now, if we go to our parent component, App, we can see the SearchInput here has no props, but we just defined that'll have autoFocus. Let's say autoFocus is now true and save. You can see that now our input in the browser window has the focus styles, but if we click into the browser and refresh, you'll see that this input is always autofocused.
[1:37] In summary, we used this inputRef here that we created with the useRef hook to point directly to the input DOM element here, and then focus it whenever the autoFocus prop was true. Again, use this sparingly as frameworks like React intent to update the DOM by using a virtual DOM.
Member comments are a way for members to communicate, interact, and ask questions about a lesson.
The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io
Be on-Topic
Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.
Avoid meta-discussion
Code Problems?
Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context
Details and Context
Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!