Member-only story
React Hooks: useRef, useImperativeHandle, & useLayoutEffect
Looking for a great (remote only) React Dev? Or just feel like having a chat? Visit my profile on LinkedIn and say hi! 😃
This article continues our discussion of React’s Additional Hooks. The official documentation on how to use these hooks is pretty sparse, so I feel that there’s a need to make a blog post about them. Let’s dive in and get hooked on hooks! (yeah, I know, that was pretty bad… 😂)
useRef
The traditional use of useRef
is to store a reference to a DOM node. If the DOM node updates, so does the reference. You can access it via the current
attribute on the returned variable.
const domRef = useRef()useEffect(() => {
doSomething(domRef.current) // access the DOM node here
}, [])return <div ref={domRef}><Components /></div>
But did you know that useRef
has another fantastic use?
If you have a value that you want to store and you don’t want it to change between renders, then useRef
is the hook to use!
A common mistake (that I’ve made myself) is to store and update a value between renders with useState
, even though it is not passed down as a prop to any child component. This means that every time you want to update the value…