Skip to content

Bug: Getting Cannot access refs during render error from event handler. #35040

@siamahnaf

Description

@siamahnaf

So on react official documentations, I found, it recommend to avoid direct read or write during render on ref.

Here is the docs link (under pitfall)-
https://react.dev/reference/react/useRef

And here I also found that ref is safe to use on event handler or effect.

You can read or write refs from event handlers or effects instead.

So, we can read ref.current from a onSubmit handler as it is a event handler. But when I combine it with react-hook-form I am getting the lint error with following context-

error  Error: Cannot access refs during render

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

So What I am doing on my code(see code)-

const onSubmit: SubmitHandler<ReceiptFormInput> = async (value) => {
    let sigUrl: string;
    if (sig) {
        const { blob } = await upload(ref.current?.toFile());
        sigUrl = blob?.url || ""
    } else {
        sigUrl = item.signature
    }
    if (template) {
        mutate({
            ...value,
            templateId: template.templateId,
            previewUrl: template.previewUrl,
            signature: sigUrl,
            id: item.id
        });
    }
}

this onSubmit handler is triggering from form

<form onSubmit={handleSubmit(onSubmit)}>
...
</form>

So here handleSubmit is coming from react-hook-form to disable default behavior.

We already discussed about this issues from nextjs discussion. Following is the link of that discussion

vercel/next.js#85677

Metadata

Metadata

Assignees

No one assigned

    Labels

    Status: UnconfirmedA potential issue that we haven't yet confirmed as a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions