Harry Yates
I'm a web developer focused on TypeScript, React, and Three.js.
It's like creating a bookmark so you can quickly find and interact with a specific part of your webpage (such as a video player or an input field) without having to search the entire page every time.
Imagine you have a book (your component) and want to quickly mark a page (a DOM element) to open it later. You insert a bookmark (useRef
) on that page. Now, you can open the book directly to that page without flipping through it whenever you want.
Example: If you have a video on your website and you want to play or pause it with a button, you can use useRef
to mark the video. Later, you just tell React, "Hey, go to the bookmark and play the video," without React needing to search for the video again.
useRef
hook (named export) from the react
package. import {useRef} from "react";
.const inputRef = useRef();
.ref
attribute. For example, <input ref={inputRef} />
.You might be tempted to use refs in every component, but refs are not commonly used. There are specific use cases for when refs should be used, such as:
videoElement.play()
), pausing a video, etc.useRef
isn't just for bookmarks in a book. It can also be like a pocket in your notebook where you can keep notes or reminders.
These notes are special because changing them doesn’t require rewriting the whole page (or re-rendering your component).
These are things that can change, like scores in a game or a stopwatch timer.
With useRef
, you can change these values all you want; the rest of the page doesn't need to be updated (or re-render) every time a change happens.
useRef
helps maintain smooth and responsive user interfaces. Re-renders can be costly, especially for complex components or applications, requiring recalculating the component's state and potentially re-executing side effects.
The pocket in your notebook (or useRef
) keeps your notes safe even if you turn the page. Similarly, useRef
keeps the values safe and unchanged through re-renders of your component.
Updating a useRef
value is like changing the note in your pocket; the notebook’s page stays the same.
This means your component doesn't update its appearance because something useRef
changed.
It's perfect when you need to keep track of something continuously (like a timer) or control parts of your webpage (like a video or animation) without updating the whole page every time something small changes.