Using useRef Hooks in React Applications

    Friday, June 28, 20248 min read352 views
    Using useRef Hooks in React Applications

    Functional Component

    Functional components in React are fantastic for building UIs declaratively, but what if you need to interact with the underlying DOM elements directly? Here’s where the useRef hook comes in.

    In a React component, useState and useReducer can cause your component to re-render each time there is a call to the update functions, including the initial render.

    In this article, you will find out what is useRef in React and how to use the useRef() hook to keep track of variables without causing re-renders, and how to enforce the re-rendering of React Components.

    React’s functional components, introduced with Hooks in version 16.8, revolutionized how we build user interfaces. Their declarative nature streamlines development, but there are situations where you might crave more control over DOM manipulation or require values to persist between renders without causing re-renders themselves. This is where the useRef hook shines.

    Unlike createRef, which returns a new ref object on every render, useRef returns the same ref object throughout the component's lifecycle.

    What is useRef hook for accessing dom elements?

    Imagine you’re building a house (your React component) with Legos (React code). Normally, you can only control how the Legos fit together by following the instructions (your component’s code). But what if you wanted to reach in and touch a specific Lego after it’s built (interact with a DOM element)?

    You can use useRef in React to create a reference to an input element, allowing you to manipulate it directly.

    The useRef hook is one of the built-in hooks in React. You can use it to persist or preserve value between re-renders. The useRef hook takes an initial value of any type as argument and returns a plain JavaScript object with a single current property.

    That’s where the useRef hook comes in. It’s like a special tool that lets you create a little sticky note (the ref object) inside your house. You can write on the sticky note (set an initial value) and then use it later to find and touch that specific Lego (access a DOM element) even after your house is built (after the component renders).

    The cool thing is that this sticky note stays put, even if you rearrange some of the Legos in your house (during re-renders). And even cooler, writing a new message on the sticky note (updating the ref’s value) won’t cause you to rebuild the entire house (it won’t trigger a re-render)!

    Secure User Access and Data With React
    Angular Minds a
    React Development Company is proficient in safeguarding your React application and user information with authentication and authorization.

    When Can You Use useRef?

    So, useRef is handy when you need to:

    Touch specific building blocks (DOM elements) in your React house (component).

    Remember things inside your house (component) that don’t affect how it looks (doesn’t cause re-renders).

    const ref = useRef(initialValue);

    In React, the useRef hook creates a ref object that you can use to access DOM elements and store mutable values without causing re-renders. When you pass an initial value to useRef, this value is set as the current property of the ref object.

    For example, if you pass the boolean value true as the initial value, the ref object will look like this: { current: true }. If you don’t provide an initial value, the current property will be undefined.

    The ref object's current property is used to reference the DOM element after rendering and can be updated or set to null when manipulating or removing the corresponding DOM elements.

    Here’s a simple example to illustrate how useRef works in a functional component:

    import React, { useRef } from 'react';
    function MyComponent() {
    
    // Create a ref object with an initial value of true const myRef = useRef(true);
    // Accessing the current property of the ref object console.log(myRef.current); // true
    
    return ( <div> <input ref={myRef} /> </div> ); }
    export default MyComponent;

    useRef hook Advantages and initial value

    • Accessing DOM elements: useRef hook Easily access and manipulate DOM elements in functional components without causing re-renders.

    • Initial Value: Store an initial value in the ref object which is preserved across re-renders.

    • Avoiding Re-renders: Store mutable values that don't trigger a component re renders of the react component when updated.

    • Ref Attribute: Attach the ref attribute to any DOM element to easily reference it.

    • Current value: The ref object's current property provides a way to directly access the stored value or DOM node.

    • DOM Manipulation: useRef hook Perform DOM manipulation without relying on state and causing unnecessary re-renders.

    • Minimal Overhead: Lightweight and simple to implement, providing an efficient way to handle references and mutable value.

    • Parent Components: In a parent component, you can use the useRef hook to create a ref object and pass it down to child components. This allows the parent component to directly access and manipulate the DOM elements or values within the child components.

    Conclusion

    In conclusion, the React useRef hook is a powerful tool for managing DOM elements and mutable values within functional components. By storing an initial value or DOM reference in the ref object's current property, useRef allows you to access and manipulate these elements without triggering re-renders.

    This makes it ideal for tasks like accessing input fields, maintaining persistent values across renders, and handling direct DOM manipulation efficiently. Whether you're working in parent components or child components, useRef provides a straightforward and effective way to extend the capabilities of your React applications.

    24

    Related articles

    This website uses cookies to analyze website traffic and optimize your website experience. By continuing, you agree to our use of cookies as described in our Privacy Policy.