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

Application Modernization: 3 Tips for Efficiency and Innovation

Software Modernisation, Web development, Managed Hosting, Hosting, Business software, Knowledge Base

Learn how application modernization can help your organization. Discover tips for efficient and cost-effective application modernization.

Read more

Tailor Your CRM to Fit Your Unique Business Processes

Automate, Logistics, Web development, Software Modernisation, B2B, Saas, Business software, Symfony, PHP, HTML & CSS, MySQL, Bootstrap, Node, React

4BIS Innovations specializes in custom CRM solutions for businesses in Limburg and Maastricht. We offer CRM development, software modernization, and seamless integration to improve efficiency, data management, and customer experience.

Read more

What is SaaS? Exploring the Future of Software Solutions

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

Discover how SaaS (Software as a Service) can benefit your business with cost-effective, scalable, and secure solutions. Learn more about SaaS applications and why they're the future of business software.

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