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

Artificial Intelligence vs Machine Learning: This is the Difference

Software Modernisation, Knowledge Base, Automate, Web development

Nowadays, many terms are thrown around interchangeably. You sometimes hear about Artificial Intelligence, but also about Machine Learning and perhaps even Deep Learning. This can make it quite unclear what exactly the term is that you are looking for...

Read more

5 Reasons Why You Want to Connect All Your Tools

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

Integrations are extremely important to ensure smooth collaboration between all your tools. Unfortunately, it still often happens that companies make some activities run less smoothly by not properly linking their tools. This is of course a shame because...

Read more

No secure server connection: These are the most common connection errors

Knowledge Base

Error messages when looking up a website are common. Although they are often easy to solve, they still often go wrong. This could be due to a small error, but this can immediately prevent a connection error. Resolving these errors requires some steps....

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