React "Cannot access refs during render" error but I am not accessing ref

2 weeks ago 16
ARTICLE AD BOX

I am trying to pass a ref to a custom function, but I'm getting an error on dialog.ref. I am not sure why because I am not accessing ref.current here, just passing the ref to the component. For some reason, destructuring the hook's return value works fine, but I prefer the dialog.ref way since I may have multiple dialogs (dialogA.ref , dialogB.ref).

Error: Cannot access refs during render

React refs are values that are not needed for rendering. Refs should only be accessed outside of render, such as in event handlers or effects. Accessing a ref value (the current property) during render can cause your component not to update as expected (https://react.dev/reference/react/useRef).

Code:

export type DialogProps = ComponentPropsWithRef<"dialog">; export function Dialog({ className = "", ...props }: DialogProps) { return ( <dialog className={`ui-dialog ${className}`} {...props} /> ); } export type UseDialogReturnType = { ref: RefObject<HTMLDialogElement | null>; isOpen: boolean; handleOpen: () => void; handleClose: () => void; }; export function useDialog(): UseDialogReturnType { const ref = useRef<HTMLDialogElement>(null); const [isOpen, setIsOpen] = useState<boolean>(false); const handleOpen = () => { if (ref.current) { ref.current.showModal(); setIsOpen(true); } }; const handleClose = () => { if (ref.current) { ref.current.close(); setIsOpen(false); } }; return { ref, isOpen, handleOpen, handleClose, }; } export function MyComponent() { const dialog = useDialog(); const { ref } = useDialog(); return ( <> <Dialog ref={dialog.ref} /> {/* Error: Cannot access refs during render */} <Dialog ref={ref} /> {/* This works for some reason */} </> ) }
Read Entire Article