Home > Web Front-end > JS Tutorial > Understanding useRef: A Beginners Guide

Understanding useRef: A Beginners Guide

WBOY
Release: 2024-09-03 13:32:32
Original
1169 people have browsed it

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
Copy after login

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 (
    <div>
      <p>Count: {countRef.current}</p>
      <button onClick={increment}>Increment</button>
    </div>
  )
}

export default App
Copy after login

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 (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
    </div>
  )
}

export default App
Copy after login

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(
    <input ref={inputRef} />
  )
}
Copy after login

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 <MyInput ref={inputRef} />;
Copy after login

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 <MyInput value={value} ref={inputRef} />;
Copy after login

Custom component:

import { forwardRef } from 'react';

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

export default MyInput;
Copy after login

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.

The above is the detailed content of Understanding useRef: A Beginners Guide. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template