In this blog, we will be seeing everything about UseRef Hook in ReactJs.
What is useRef Hook?
useRef
is a hook in React, a popular JavaScript library for building user interfaces. It's used to create a mutable reference that persists across renders of a functional component. This reference can be used to store and access a value that doesn't trigger a re-render when it changes, unlike the state or props of a component.
When to use useRef Hook?
The useRef
hook in React is primarily used to access and interact with DOM elements or to maintain mutable values across renders without causing a re-render when the value changes. Here are some common scenarios where you might want to use the useRef
hook:
Accessing DOM Elements*:* When you need to access a DOM element directly, such as to read its properties or to modify it imperatively (outside of React's declarative paradigm), you can use
useRef
. This is a common use case when you're integrating third-party libraries or interacting with lower-level DOM APIs.import { useRef, useEffect } from 'react'; function MyComponent() { const myElementRef = useRef(null); useEffect(() => { // Access and manipulate the DOM element if (myElementRef.current) { myElementRef.current.focus(); } }, []); return <input ref={myElementRef} />; }
Preserving Values Across Renders*:* When you have a value that you want to keep between renders, but changing it shouldn't trigger a re-render, you can use
useRef
. This is often used for values that are used for computation or side effects but don't affect the UI rendering.import { useRef, useState } from 'react'; function MyComponent() { const counter = useRef(0); // Preserves value across renders const incrementCounter = () => { counter.current += 1; console.log('Counter:', counter.current); }; return ( <div> <button onClick={incrementCounter}>Increment Counter</button> </div> ); }
Storing Previous Values:
useRef
can be used to store the previous value of a state or prop so that you can compare it with the current value in auseEffect
or other hooks.import { useRef, useEffect } from 'react'; function MyComponent({ value }) { const prevValueRef = useRef(); useEffect(() => { if (prevValueRef.current !== value) { console.log('Value changed:', value); prevValueRef.current = value; } }, [value]); return <div>{value}</div>; }
Remember that useRef
does not trigger a re-render when its value changes, so it's not suitable for managing state that requires UI updates. If you need to manage state that causes UI updates, you should use the useState
or other appropriate hooks.
Why to use useRef Hook?
The useRef
hook in React is used primarily to access and interact with DOM elements and to manage values that persist across renders without causing re-renders themselves. It's a way to retain values between renders of a component without triggering a re-render when the value changes.
Here are some common use cases for the useRef
hook:
Accessing DOM Elements: When you need to interact with a DOM element directly, such as focusing an input, scrolling to a specific point, or measuring an element's dimensions,
useRef
can be used to create a reference to that DOM element.Preserving Values across Renders: Unlike
useState
, updating the value of auseRef
doesn't trigger a re-render of the component. This makes it useful for storing values that you want to persist between renders without causing unnecessary re-renders. For instance, you might use it to store a previous state value for comparison, to track whether a component is mounted or not, or to store a value that is part of a computation but doesn't need to trigger re-renders.Caching Expensive Computations: If you have a computation that is resource-intensive and doesn't need to be recomputed on every render, you can use
useRef
to cache the result. This can help optimize the performance of your component.Preserving Mutable Values:
useRef
can be used to store mutable values that don't trigger re-renders. This can be handy when dealing with values that should not be part of the component's state but need to be accessed across renders.Storing Previous Values for Comparison: You can use
useRef
to store the previous value of a prop or state, allowing you to compare it with the current value and take actions based on the change.
Difference between useRef and other ref approaches
In React, refs are a way to directly interact with DOM elements or class components. They provide a way to access and manipulate these elements or components outside of the normal React data flow. React provides different approaches for creating refs, and one of those approaches is useRef
.
useRef
is a Hook in React that returns a mutable ref object. This ref object can hold a reference to a DOM element or a value, and it persists across renders. The key feature of useRef
is that it doesn't cause a re-render when the ref's value changes. It's commonly used to access DOM elements directly, manage focus, and to store values that don't trigger re-renders but need to persist between renders.
Other approaches to creating refs in React include React.createRef()
and callback refs. Here's a comparison of these approaches:
React.createRef()
:This is a method that's typically used in class components.
It returns a ref object that can be attached to React elements using the
ref
attribute.The ref can be used to access the DOM element or class component instance.
It can't be used in functional components without a workaround, as it requires class component instance methods.
Callback Refs
:Callback refs involve using a function to create and update refs.
In functional components, you define a function that takes a parameter (the DOM element or component instance) and does something with it (like storing it in a state).
These refs are defined within the functional component's scope, so they can work with functional components more easily.
Callback refs are less concise compared to
useRef
.
useRef
:This Hook was introduced in React to cover the use cases of refs in functional components.
It returns a ref object that remains the same across renders, making it suitable for holding values that shouldn't trigger re-renders.
It's commonly used for accessing DOM elements, maintaining mutable values, and in scenarios where the previous ref value needs to be retained.
Since it's a Hook, it fits well into the functional component model and doesn't require the verbose syntax of callback refs.
In summary, useRef
is the preferred approach for managing refs in functional components due to its simplicity and compatibility with the functional component paradigm. If you're working with class components, you can use React.createRef()
. Callback refs are an older approach that's still used, but they're less concise and more error-prone compared to the useRef
Hook.
Implementation of UseRef Hook
To see and understand the implementation of uesRef
we will create a button
and when the button is clicked it should print Hello World!!
.
Step 1: Basic structure of our page
Step 2: Styling our page
Step 3: Creating a useRef variable and importing it from react
Step 4: Giving reference variable to ref
attribute of our button
Step 5: Creating button
variable inside uesEffect and giving the current reference to this variable
Step 6: Adding onclick
EventListener on this reference
Step 7: Adding a for loop
to print Hello World!!
Step 8: Final output
So, in this blog, we learned about UseRef Hook in ReactJS, When to use UseRef Hook, Why to use UseRef Hook, Difference between useRef and other ref approaches and The implementation of UseRef Hook . There is much more to learn about UseRef Hook in ReactJS, explore this topic and its used cases and elevate your skills.
Adios Amigos 👋👋