DEV Community

Discussion on: A Quick Guide to Understanding React Hooks

Collapse
 
eecolor profile image
EECOLOR

Hello, thank you for writing the article!

From the article it seems your understanding of the useRef hook is a bit limited. Another way to describe a ref is to say: a piece of state that does not cause a re-render when changed. On top of that it is constructed in a way that ensures it is 'referentially stable'.

You could see it like this:

const myRef = { current: null }

function doSomething() {
  if (!myRef.current) myRef.current = 0
  myRef.current++
}
Enter fullscreen mode Exit fullscreen mode

The useRef function ensures that myRef is attached to the 'instance' of your component and will be removed once the component is unmounted.

useRef can be very useful in a variety of situations, here is an example:

function useOnClick(f) {
  const callbackRef = React.useRef(null)
  callbackRef.current = f

  React.useEffect(
    () => {
      document.addEventListener('click', handleClick)
      return document.removeEventListener('click', handleClick)

      function handleClick(e) {
        callbackRef.current(e)
      }
    },
    []
  )
}
Enter fullscreen mode Exit fullscreen mode

Here we are using useRef instead of passing f as a dependency to useEffect to prevent listeners to be added and removed on each render.

I hope this provides a bit of extra understanding.

Collapse
 
ash_bergs profile image
Ash • Edited

I really appreciate your comment!

I'm definitely still learning, and this was very helpful. I'll be amending some notes and testing this approach out in some code ASAP. Thank you for taking the time to help me understand this topic more deeply.