In this post, we'll cover what the useRef hook is, some examples of how it can be used, and when it shouldn't be used.
What is useRef?
...
Some comments have been hidden by the post's author - find out more
For further actions, you may consider blocking this person and/or reporting abuse
What are some other use cases you've used the
useRef
hook for?I once had some variables causing my hook to re-render infinitely. Fixed it by storing the variables using useRef
Besides accessing DOM elements, I've primarily used
useRef
for handling websockets (similar to your case), managing formData values, SVG drawing, and integrating third-party APIs that weren't designed for use with React.Nice! Thanks for sharing, Giovanni.
When you want track any kind of value and don't want to trigger rerender of components when that value is updated, that's the perfect use case of useRef.
In simple words when don't want to link the state to the UI.
Basically for any kind of value which should be be stored across but should not trigger a rerender.
Pretty much that. Thanks for giving it a read Red!
Have used it to replace useMemo and useCallback.
Great place to store an abort controller that can be accessed by several functions.
Yeah, that's another great example @link2twenty! Do have any example code lying around to share in a gist or CodeSandbox?
Here is a quick demo I just threw together. AbortController's are super good at preventing your frontend app spamming endpoints.
codesandbox.io/p/sandbox/abort-con...
Thanks for sharing!
Update 2024/07/20:
I updated the code sample below as @jgarplind pointed out to me on DMs over on Bluesky, that
firstNameInputRef.current
is not necessary in the dependency array and is misleading potentially to devs that you need it. Thanks, Joel!Informative
Glad you found it informative!
Interesting topic! Everything is explained articulately and clearly. For your project, consider checking out this free npm package: select-paginated.