Member-only story

React Hooks: useRef, useImperativeHandle, & useLayoutEffect

Ben Grunfeld
4 min readJul 29, 2020

Looking for a great (remote only) React Dev? Or just feel like having a chat? Visit my profile on LinkedIn and say hi! 😃

React additional hooks

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…

--

--

Ben Grunfeld
Ben Grunfeld

Written by Ben Grunfeld

I’m a Front End Engineer who loves React, NextJS, and GraphQL. Looking for a developer in #Israel? Contact me at: https://www.linkedin.com/in/bengrunfeld/

No responses yet