React Refs

Published on
3 mins read
––– views

Ref can be manipulated

If you've read a post or two on my blog, you may have noticed that I always advise against mutating the React State. This still holds true. However, Refs can be mutated, and they are meant to be.

When do we use Ref?

Refs allow us to access DOM elements and newly rendered components, as well as manipulate them. We use refs to get a reference to a particular component.

Refs are most commonly used to focus on an input field, measure dimensions or the location of the cursor. They can also be used to interact with a child component from the parent component.

For example:

import React, { useRef } from 'react'

function MyComponent() {
  // create a ref using the useRef hook from React
  const myRef = useRef(null)

  function handleClick() {
    myRef.current.focus()
  }

  return (
    <div>
      <input type="text" ref={myRef} />
      <button onClick={handleClick}>Focus Input</button>
      {/* Clicking this button will activate the handleClick function and the input field will be in focus. */}
    </div>
  )
}

Do not overuse useRef

What, what? I can hear you asking. Ref is great and can be a life saver,

BUT:

With great power comes great responsibility - Uncle Ben

If you can achieve what you want to achieve without using Ref do not use Ref. There are few reasons behind this idea.

  • Using ref's makes the code harder to read and understand

Brain W. Kernighan has a great quote

Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it

If you use Ref as cleverly as possible, a month or two later down the road your code will make no sense at all. When the cheesecake hits the fan, and you face random errors and bugs, you will understand the value of the writing dumb code.

  • The thing about useRef in React is that it breaks the normal data flow and bypasses the virtual DOM.

Sure, React can handle it, but it can make code harder for us humans to understand. Reading someone else's code is already hard enough, but when it doesn't follow typical design patterns, it's a nightmare. If you're not familiar with the codebase and there are Ref pointing to everything, good luck trying to figure out what's going on.