Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

51
Views
Creating a custom Hook that includes useRef

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>
  );
}
about 4 years ago · Santiago Gelvez
2 answers
Answer question

0

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);
about 4 years ago · Santiago Gelvez Report

0

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>
  );
}
about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!