"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Understanding useRef: A Beginners Guide

Understanding useRef: A Beginners Guide

Published on 2024-09-11
Browse:121

Understanding useRef: A Beginners Guide

Introduction

What is useRef

useRef is React hook that allows to create a persistent reference to a value or a DOM element. Unlike useState, which is used to manage state that triggers re-renders, useRef is primarily used for side effects or accessing DOM elements directly.

Why use useRef

The useRef hook is particularly useful for:

  • Accessing DOM elements directly: you can use useRef to get a reference to a DOM element, allowing you to manipulate it directly without triggering a re-render.
  • Create persistent values: Unlike state, values created with useRef persist between renders, making them ideal for storing data that doesn't need to trigger re-renders.

Understanding the useRef hook

The useRef hook returns an object with .current property. when you call useRef, it creates a persistent reference to the value you pass as argument. This reference is stored in .current property of the returned object.

Creating a reference with useRef

To create a reference simply call useRef with initial value.

import { useRef} from 'react'

const App = () => {
  const countRef = useRef(0)

  return (...)
}

export default App

In the above example countRef is a reference to the initial value 0.

Accessing the reference value

To access the reference value just call the countRef object with .current property

import { useRef} from 'react'

const App = () => {
  const countRef = useRef(0)

  const increment = () => {
    countRef.current  
  }

  return (
    

Count: {countRef.current}

) } export default App

In the above example if you click the button it will call the increment function which will increase the countRef, but the count won't be updated at

Count: {countRef.current}

because updating useRef don't cause re-renders like useState.

update the code to example below to get the result you expect.

import { useRef, useState } from 'react'

const App = () => {
  const countRef = useRef(0)
  const [count, setCount] = useState(0)

  const increment = () => {
    countRef.current  
    setCount(countRef.current)
  }

  return (
    

Count: {count}

) } export default App

Common use cases for useRef

Directly accessing and manipulating DOM elements

it's possible to use useRef hook to access and change the properties of html elements

const App = () => {
  const inputRef = useRef(null)

  const handleFocus = () => {
    inputRef.current.focus()
  }

  return(
    
  )
}

Persistent Values

Unlike useState or variable, useRef can pass values and data between re-renders such as cached data or configuration settings.

Performance Optimization

In some cases, using useRef can help with component optimization by avoiding unnecessary re-renders. like if you have a component that renders a large list of items you can cache it using useRef and only modify re-render the items that have changed.

Best practices and considurations

  • Do not write or read ref.current during rendering
  • You can mutate the ref.current property
  • When you change the ref.current property, React does not re-render your component
  • The information is local to each copy of your component (unlike the variables outside, which are shared).You can store information between re-renders (unlike regular variables, which reset on every render).
  • You can read or write refs from event handlers or effects instead.
  • Manipulating the dom with ref

Passing a ref to custom component.

If you try to pass a ref to your own component like this

const inputRef = useRef(null);

return ;

You might get an error in the console:
Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

To solve this issue wrap the custom component with forwardRef like so:

const inputRef = useRef(null);

return ;

Custom component:

import { forwardRef } from 'react';

const MyInput = forwardRef(({ value, onChange }, ref) => {
  return (
    
  );
});

export default MyInput;

Conclusion

useRef is a powerful hook that is primarily used for side effect usage like caching data between re-renders or accessing elements of the DOM. It's a great tool for performance optimization and achieving specific functionalities in React application.

Release Statement This article is reproduced at: https://dev.to/kada/understanding-useref-a-beginners-guide-58bg?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3