• Home
  • React
  • React Hooks – useRef hook example

React Hooks – useRef hook example



UseRef hook can be used in two ways. First, it allows to directly access to DOM element, so we can manipulate it. Second, it can keep any mutable value in its .current property, that is not change between renders.

When value of useRef hook has change, it will not cause component re-render. Lets create some example.

We create an input element and pass it to the useRef hook. Next, we create button, which after clicking it causes displaying input value in paragraph (which we pass to another ref, se we can have easy access to it). When value on page will change, it will not cause component re-render.

import React, { useRef } from 'react';

const HookExample = () => {    
    const inputEl = useRef(null);
    const paragraphEl = useRef(null);
    
    console.log("component has just rendered");

    return (
        <div className="App">
            <input ref={inputEl} type="text" />
            <div>
                <button onClick={() => {
                            paragraphEl.current.innerText = inputEl.current.value;
                            inputEl.current.value = "";
                        }}>Display input value</button>
                <p ref={paragraphEl} >Display input value here </p>
            </div>
        </div>
    );
}

export default HookExample;


We can also use useRef hook to keeping any mutable value. If we set useRef value to 0, then after component renders we can change it for example to string:

const HookExample = () => {    
    const paragraphEl = useRef(null);

    // useRef hook can also hold a mutable value in its .current property
    const counter = useRef(0);
   
    useEffect(() => {
        console.log(counter.current);          // 0
        counter.current = "yo!";
        console.log(counter.current);          // "yo!"
    });

    return (
        <p ref={paragraphEl} >Some text here </p>
        <button onClick={() => paragraphEl.current.innerText = counter.current}>Display counter value</button>
    );
}

export default HookExample;

After clicking on “Display counter value” button in paragraph will display “yo!” text.

Click on DEMO to see how useRef hook works

You can find this code in repo: https://github.com/love-coding-pl/React-Hooks-Examples/tree/Hook-5-useRef

Joanna

Leave a Reply

Your email address will not be published. Required fields are marked *