DEV Community

Cover image for React Custom Hooks (useRefs)
sundarbadagala
sundarbadagala

Posted on

React Custom Hooks (useRefs)

INTRO ๐Ÿ””
Hello World! ๐Ÿ‘‹
Today we are discussing another custom hook๐Ÿช is useRefs๐Ÿ”ฅ. It is an extension of useRef๐Ÿ’ฅ. Now we will see the code and how to use it.

USAGE ๐Ÿ””

As a React developer๐Ÿง‘๐Ÿปโ€๐Ÿ’ป , we all know what useRef๐Ÿ’ฅ hook is. useRef๐Ÿ’ฅ helps to access the DOM elements. One useRef๐Ÿ’ฅ will help to access one element but sometimes we need to access more than one element ๐Ÿค”. That time we need to create multiple uesRef๐Ÿ’ฅ hooks. To avoid this problem we are creating a useRefs๐Ÿ”ฅ custom hook.

Note๐Ÿ“Œ :- As discussed earlier hook useLocal๐Ÿš€. This is not a hook, it is the helper. But for our convenience, we are calling it a hook๐Ÿช.

CODE ๐Ÿ””

export const useRefs = () => {
  const refs = [];
  return [refs, (el) => el && refs.push(el)];
};
Enter fullscreen mode Exit fullscreen mode

USE CASE ๐Ÿ””

TRADITIONAL MULTIPLE useRef HOOKS ๐Ÿ•ฏ๏ธ

import React, { useEffect, useRef } from "react";

function App() {
  const headerRef = useRef(null);
  const inputRef = useRef(null);
  const btnRef = useRef(null);
  useEffect(() => {
    console.log("header", headerRef.current.innerText);
    console.log("input", inputRef.current.defaultValue);
    console.log("button", btnRef.current.offsetWidth);
  }, []);
  return (
    <>
    <main>
        <div id="header" ref={headerRef}>Header</div>
        <input type="text" defaultValue={'hello world'} ref={inputRef}/>
        <button id="click" ref={btnRef}>Click Here</button>
    </main>
    </>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

USING useRefs HOOK ๐Ÿ’ก

import React, { useEffect } from "react";
import { useRefs } from "./useRefs";

function App() {
  const [refs, handleRef] = useRefs();
  useEffect(() => {
    console.log("header", refs[0].innerText);
    console.log("input", refs[1].defaultValue);
    console.log("button", refs[2].offsetWidth);
  }, []);
  return (
    <>
      <main>
        <div id="header" ref={handleRef}>Header</div>
        <input type="text" defaultValue={"hello world"} ref={handleRef} />
        <button id="click" ref={handleRef}>Click Here</button>
      </main>
    </>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

It also gives the same output as using multiple useRef hooks.

Please practice in your Code Editor, you will get full clarity on this hook.

CONCLUSION ๐Ÿ””

I hope this hook is helpful. We will meet with another hook in another post.

Peace ๐Ÿ™‚

Top comments (0)