Home > Software design >  Creating a custom Hook that includes useRef
Creating a custom Hook that includes useRef

Time:07-19

In the following code I create a hook that uses useState inside it, the hook works perfectly. Then I create a second custom hook that inside uses a useRef to print an html element in the console, the latter doesn't work because I don't know how to refer to the element from the hook I'm creating. Here the code:

import "./styles.css";
import {useEffect, useRef, useState} from "react"

function useChangeText(){
  const [n,setN]= useState(0)
  const sum= ()=> setN(n   1)
  return {number:n,sum}
}

function useGetHTML(n){
  const element= useRef(null)
  useEffect(()=>{
    console.log(element.current)
  },[n])
}

export default function App() {
const hookSum= useChangeText()
const element= useGetHTML(hookSum.number)

  return (
    <div ref={element} className="App">
      <h1>{hookSum.number}</h1>
      <button onClick={hookSum.sum}>click  1</button>
    </div>
  );
}

CodePudding user response:

It is a matter of exporting the ref created from your useGetHTML hook so that it can be used by your consuming component, just like you did in the useChangeText hook:

function useGetHTML(n){
  const element = useRef(null);
  useEffect(()=>{
    console.log(element.current)
  },[n]);
  
  return element;
}

Then in your component, the element will no longer be undefined but will be the exported ref from your custom hook:

const element = useGetHTML(hookSum.number);

CodePudding user response:

You don't need useRef nor useEffect for that.

You can pass a setter callback to ref= it will be called with your element once your component is mounted:

import "./styles.css";
import {useState} from "react"

function useChangeText(){
  const [n,setN]= useState(0)
  const sum= ()=> setN(n   1)
  return {number:n,sum}
}

function useGetHTML(n){
  const [element, setElementRef] = useState(null)
  if (element) { // just use if here
    console.log({ element, n })
  }
  return setElementRef
}
export default function App() {
const hookSum= useChangeText()
const setElementRef= useGetHTML(hookSum.number)

  return (
    <div ref={setElementRef} className="App">
      <h1>{hookSum.number}</h1>
      <button onClick={hookSum.sum}>click  1</button>
    </div>
  );
}
  • Related