Delay in updating state value when using ref with textarea in React

31 Views Asked by At

I'm encountering a delay in updating the promptValue state when I use a ref with the textarea component in Next. Here's a simplified version of my code:

    const handlePromptChange = (evt: React.ChangeEvent<HTMLTextAreaElement>) => {
  const val = evt.target?.value;
  setPromptValue(val);
};

<textarea
  ref={textAreaRef}
  onChange={handlePromptChange}
  onClick={handleCloseSidebar}
  onKeyDown={handleKeyPress}
  rows={1}
  value={promptValue} 
  readOnly={loading}
/>

export const useAutosizeTextArea = (
  textAreaRef: HTMLTextAreaElement | null,
  value: string,
) => {
  useEffect(() => {
    if (textAreaRef) {
      const scrollHeight = textAreaRef.scrollHeight;
      textAreaRef.style.height = scrollHeight + "px";
    }
  }, [textAreaRef, value]);
};

The issue is that when I introduce a ref to the textarea, there's a noticeable delay in updating the promptValue.

0

There are 0 best solutions below