What’s the correct way to use useRef and forwardRef together?

You can largely ignore the TS error because you didn’t provide types for the forwardRef arguments so it doesn’t know that ref/innerRef are equivalently typed.

const divElement = ref || innerRef; <div ref={divElement}></div>

I don’t understand this bit – do you want it to have a reference to the div element directly regardless of if the is given a ref or not?

Anyway, I think if you want to get it working like this, it’s best you use the useImperativeHandle hook like useImperativeHandle(ref, () => innerRef.current);

So, the Child component itself manages the ref with the innerRef but if someone does pass a ref to the Child component, it will yield that.


export default React.forwardRef((props, ref) => {
  const innerRef = useRef<HTMLDivElement>(null);

  useImperativeHandle(ref, () => innerRef.current);

  useEffect(() => {
    if (innerRef.current) {
      console.log("clientWidth: ", innerRef.current.clientWidth);
    }
  }, []);

  return <div ref={innerRef}></div>;
});

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)