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...

WordPress and Plugins – A world that opens up for you!

WordPress, Web development, Ecommerce / Webshop, Knowledge Base, WooCommerce

With plugins you can expand the functionality of WordPress or add completely new functions to WordPress. You can make plugins yourself, provided you know PHP, or you can download them.

Read more

Unveiling Tech-Nieuws.nl: Where Innovation Meets Ingenuity

SEO / SEA, Software Modernisation, Web development, PHP, Symfony, Digital Marketing

In the bustling realm of technology, staying updated is not just a necessity but a lifestyle. With an overflow of information bombarding us daily, having a reliable source to curate and present the latest tech news becomes invaluable. Enter Tech-Nieuws.nl,...

Read more

HR software: This is how you automate Human Resource Management

Business software, Software Modernisation, Web development, Automate

HRM, also known as Human Resource Management, is an important part for every company. Especially if you have many employees, an HR department is indispensable. However, it is not necessary to have a huge HR department. Much can be automated using HR...

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