In this lesson we replace React.createRef()
with the React.useRef
hook. The API is almost identical, so the there's not much to it, if you're already familiar with refs.
In React, refs provide a way to store references to native DOM elements. Throughout React's evolution there have been several variations on the pattern including callback refs and string refs. With functional components you'll only want to be using the useRef()
hook to create your refs.
One other thing to note about refs is that you can only pass them in to class components and built-in components (such as <div>
). If you need to pass a ref
into a function components check out the forwardRef API.
Callback Refs
This lesson does not cover callback refs, but if you have one like this one and you wanted to migrate it to useRef()
class MyComponent extends React.Component {
render() {
return (
<input type="text" ref={el => this.inputRef = el} />
)
}
}
It would look like this:
function MyComponent() {
const inputRef = useRef();
return <input type="text" ref={inputRef} />
}