Logo

dev-resources.site

for different kinds of informations.

Understanding useRef: A Beginners Guide

Published at
9/2/2024
Categories
useref
webdev
react
javascript
Author
kada
Categories
4 categories in total
useref
open
webdev
open
react
open
javascript
open
Author
4 person written this
kada
open
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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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 <p>Count: {countRef.current}</p> 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
Enter fullscreen mode Exit fullscreen mode

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} />
  )
}
Enter fullscreen mode Exit fullscreen mode

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} />;
Enter fullscreen mode Exit fullscreen mode

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} />;
Enter fullscreen mode Exit fullscreen mode

Custom component:

import { forwardRef } from 'react';

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

export default MyInput;
Enter fullscreen mode Exit fullscreen mode

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.

useref Article's
29 articles in total
Favicon
How to create components interfaces using useRef/forwardRef/useImperativeHandle
Favicon
Hooks Behind The Scenes 3, UseRef!!!
Favicon
Mastering React's useRef Hook: Working with DOM and Mutable Values
Favicon
Understanding useRef: A Beginners Guide
Favicon
useRef Hook Explained
Favicon
useRef() in React . . .
Favicon
React State Management: When & Where add your states?
Favicon
Unlocking the Power of useRef: Besic to Advanced Examples for React Developers
Favicon
Leveraging useRef in TypeScript for Efficient DOM Manipulation
Favicon
Unlocking the Power of React Hooks
Favicon
React.useRefの理解を含めるエクササイズ
Favicon
Mastering React's useRef Hook: A Deep Dive
Favicon
Unlocking the Power of useRef in React: 12 Essential Use Cases
Favicon
Série React Hooks: useRef
Favicon
Toggle Password Visibility Using React useRef
Favicon
Stop using useState for everything
Favicon
Using React hooks to develop a Video Player
Favicon
React - How to load a form with the latest data
Favicon
React: сфокусировать поле ввода по чекбоксу
Favicon
How do I check/uncheck all checkboxes with a button In React Js using useRef() Hook ?
Favicon
Multiple item using one ref
Favicon
Closures and useEffects
Favicon
I need help. TypeError: Cannot read properties of undefined (reading 'current')
Favicon
Using React useRef Hook to access immediate past props or state.
Favicon
Compare Props in React Functional Components.
Favicon
Creating infinitely scrolling SPA using React
Favicon
useRef()가 순수 자바스크립트 객체라는 의미를 곱씹어보기
Favicon
Complete useRef() hook with live code examples
Favicon
Useful Patterns with React hooks

Featured ones: