useRef Hook

 useRef hook accepts one argument as the initial value and returns a reference.

Note: 
        1. value of reference is persisted (does not change) between component re-rendering.
        2. updating the value of the reference doesn't trigger a component re-rendering like state does.

To understand about reference more, first consider the following example:
        import { useState } from "react";
        const App = () =>{
                const [click, setClick] = useState(0);
                console.log("Rendering");

                return(
                        <>
                            <p>Clicked {click} times </p>
                            <button onClick = {() => setClick(click+1)}>Click</button>
                        </>
                );
        }

        When you run the above component, whenever you click on the button, Rendering will be printed on the console each time, because state change re-render the whole component. 

Now consider the same example but instead of useState, use useRef:

        import {useRef} from "react";
        const App = () =>{
                const click = useRef(0);
                console.log("Rendering");

                return(
                        <>
                            <p>Clicked {click.current} times </p>
                            <button onClick = {() => {
                                    click.current++;
                                    console.log(click.current);
                            }}>Click</button>
                        </>
                );
        }

Note: To access the value of a reference use ref.current

        Here you'll see whenever you click on the button, the value in console updated but rest of the component will not update and remains the same. Which means that when we've used useRef the component stops re-rendering.

        useRef can be used to access DOM elements as:
                      const name = useRef(0);
                      <input type ="text" ref = {name} />
        Here we can get the value directly from the DOM without causing the whole component to re-render.

Continue Learning: React Router

Comments

Popular Posts