Mastering React Hooks Series Unveiling the Power of useRef (Part 3)

Knowledge Base, React

Published: 31.01.2024

Welcome back to the third installment of our React Hooks series! In the previous blog posts, we delved into the fascinating world of hooks, exploring their significance and discussing essential hooks like useState, useEffect, useContext, and useReducer. These hooks empower us to replicate class-based component functionality in functional components and create a simplified Redux store. In the upcoming articles, we'll delve deeper into Redux. However, for now, let's focus on the useRef hook.

Understanding useRef:

The useRef hook is a powerful tool that grants us access to DOM nodes and allows us to persist data across rerenders. In this blog post, we'll explore how to leverage useRef for various scenarios.

Accessing DOM Elements:

One primary use case for useRef is gaining access to DOM elements. Let's consider an example where we use useRef on an input element to focus on it after a click event. Additionally, we utilize the .current property to retain the input's value. Here's a snippet of how it can be implemented:

import React, { useRef } from 'react';

const RefFunctionComponent = () => {
    const bestEredivisieClub = useRef('Ajax');

    const focusRef = () => {
        bestEredivisieClub.current.focus();
    };

    return (
        <div>
            <input
                ref={bestEredivisieClub}
                type="text"
                value={bestEredivisieClub.current}
            />
            <button onClick={focusRef}>Focus on the ref object</button>
        </div>
    );
};

export default RefFunctionComponent;

Preserving Values Across Rerenders:

Unlike the createRef API, which provides a new value after each rerender, useRef maintains its value throughout successive rerenders. In the following example, we compare the behavior of createRef and useRef when changing values after a specific time interval:

import React, { useRef, useState, createRef, useEffect } from 'react';

const RefFunctionComponent = () => {
    const [rerender, setRerender] = useState(1);
    const useRefHook = useRef('Ajax');
    const createRefAPI = createRef();

    createRefAPI.current = 'Ajax';

    useEffect(() => {
        setTimeout(() => {
            useRefHook.current = 'PSV';
            createRefAPI.current = 'PSV';
            console.log(useRefHook, createRefAPI);
        }, 5000);
    }, []);

    return (
        <>
            <p>Aantal keer gererendered: {rerender}</p>
            <p>
                <b>useRef</b> Wat is de slechtste club: {useRefHook.current}
            </p>
            <p>
                <b>CreateRef</b> Wat is de beste club:{createRefAPI.current}
            </p>

            <button onClick={() => setRerender((v) => v + 1)}>
                Cause re-render
            </button>
        </>
    );
};

export default RefFunctionComponent;

Conclusion:

As demonstrated, the useRef hook is a valuable addition to your React toolkit, providing seamless access to DOM elements and enabling the preservation of values across rerenders. Stay tuned for our next blog article, where we'll explore useMemo and useCallback. If you require assistance with your React project, our professionals are always ready to lend a helping hand.

For professional React development support, feel free to reach out to us!

Read some of our blogs down here!

Expand your knowledge with the 4BIS Blog...

what-do-api-connections-cost

Web development, Software Modernisation, Business software, Managed Hosting, Saas

API connections are essential for seamless integration between software systems, but determining the cost of creating one can be complex. In this guide, we break down the main factors that impact API development costs—including data volume, security...

Read more

5 Tips to Find the Right Software Developer

Web development, Software Modernisation, Ecommerce / Webshop, Business software, PHP, MySQL, HTML & CSS

Discover 5 essential tips for finding the right software developer, from price-quality ratio to location and experience. Read our helpful guide!

Read more

Automating your Software and Processes: Benefits and Applications

Automate, Web development, Software Modernisation, Business software, Knowledge Base

Discover how automation of your software and processes can improve your business. Learn about the benefits of automation and how it can make your operations more efficient. Contact us for customized automation solutions.

Read more

And what can we do for you?_

Do you want to know more or are you interested? Please feel free to contact us directly, by phone or via mail.
Or use one of our contact forms so that we can answer you as quickly and appropriately as possible can give. We would love to hear from you!

back to top