useRef hook in React.js

useRef hook in React.js

React is introduced hooks with the functional components. Hooks are very useful and developers friendly. Hooks allow us to reuse the stateful logic without changing your component hierarchy. We use some hooks in our daily development work like useState, useEffect But we don't use some hooks very often. useRef is one of them. We discuss about this hook in this blog. We write a word in the div tag and add other words to complete the line from outside of this div tag. We use here useRef hook. This concept will be more clear when we write code.

UseRef: useRef hook accepts an initial value and returns a reference or object.

I know you don't understand anything from the above line. Please don't quit and keep reading.

When we declare the useRef hook, it creates a space to save the reference value. Let's try to understand with code.

import React, { useEffect, useRef} from 'react';
import "./Home.css";



const Home = () => {
    const value = useRef();

    useEffect(()=>{

        console.log(value);


    },[])
    return (
        <div ref={value} className="home">
            useRef
        </div>
    );
};

export default Home;

I declare a useRef hook like any other hooks in react. Here const value = useRef() create a space in the "current" placeholder of the useRef function to store the ref value. When react find ref={value}, it saves this value in the "current" placeholder. We can console.log() the value to understand this. When we use the useRef hook, our component should be loaded. So, we use useEffect hook. Now write console.log(value) in the useEffect hook to understand how it saves the ref value.

In the first load of our page, we get this from console.log.

b.png

Now we get the class name of our div in the current object. We can access directly catch the dom node using value.current. We can select the dom node using this way and work with it.

Now, we add some other words after UseRef in the div.

import React, { useEffect, useRef} from 'react';
import "./Home.css";

const Home = () => {
    const value = useRef();

    useEffect(()=>{

        // console.log(value);
        value.current.append("catch the ref value")

    },[])
    return (
        <div ref={value} className="home">
            useRef
        </div>
    );
};

export default Home;

We select the div using value.current and use appened function to add “catch the ref value” after the useRef word in the div. appened function mainly inserted value at the end of the selected elements.

our browser looks like,

b1.png

Happy coding 👨‍💻