ReactFix
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • React
  • React Native
  • Programming
  • Object Oriented Programming

Thursday, November 17, 2022

[FIXED] How do I type a ref callback with useCallback with Typescript?

 November 17, 2022     javascript, react-hooks, reactjs, typescript   

Issue

I'm new to Typescript and can't figure out how to type this situation. I'm writing a custom hook and trying to create a callback ref. My problem is that this function sets the ref's current, and returns nothing, but since I use it as a ref, typescript yells at me Property 'current' is missing in type '(node: any) => void' but required in type 'RefObject<HTMLDivElement>'.

Thank you in advance.

This is the code:

import React, {useCallback, useRef} from 'react'

const useCustom = (): [RefObject<HTMLDivElement>] => {
  const ref = useRef<HTMLDivElement | null>(null)
  const setRef = useCallback(node => {
    ....
    ref.current = node
  }, [])

  return [setRef]
}

const SomeComp = () => {
  const [ref] = useCustom()

  return <div ref={ref}>Text</div>
}

Solution

The problem is you said the return value of useCustom would be RefObject<HTMLDivElement>, but returned (node: HTMLDivElement) => void.

Your custom hook should return 2 values: one for setting the ref value, the other for the ref itself. So it will look like useState hook:

const useCustom = (): [
  RefObject<HTMLDivElement>,
  (node: HTMLDivElement) => void
] => {
  const ref = useRef<HTMLDivElement | null>(null);
  const setRef = useCallback((node) => {
    ref.current = node;
  }, []);

  return [ref, setRef];
};


Answered By - Diyorbek Sadullaev
Answer Checked By - - Marie Seifert (ReactFix Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post Home

Featured Post

Is Learning React Difficult?

React is difficult to learn, no ifs and buts. React isn't inherently difficult to learn. It's a framework that's different from ...

Total Pageviews

Copyright © ReactFix