Cookies Psst! Do you accept cookies?

We use cookies to enhance and personalise your experience.
Please accept our cookies. Checkout our Cookie Policy for more information.

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)];
};

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;

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;

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 πŸ™‚

Last Stories

What's your thoughts?

Please Register or Login to your account to be able to submit your comment.