Skip to content

Instantly share code, notes, and snippets.

@al3xnag
Created September 18, 2025 19:21
Show Gist options
  • Select an option

  • Save al3xnag/38ea90943b72aa2eefcc9df2ca0a1d0d to your computer and use it in GitHub Desktop.

Select an option

Save al3xnag/38ea90943b72aa2eefcc9df2ca0a1d0d to your computer and use it in GitHub Desktop.
useTextareaAutogrow
import { RefObject, useEffect, useLayoutEffect } from 'react'
export function useTextareaAutogrow({
ref,
value,
enabled = true,
}: {
ref: RefObject<HTMLTextAreaElement | null | undefined>
value: string
enabled?: boolean
}) {
useLayoutEffect(() => {
if (!enabled) {
return
}
const textArea = ref.current
if (!textArea) {
return
}
textArea.style.height = 'auto'
textArea.style.height = textArea.scrollHeight + 'px'
}, [ref, value, enabled])
useEffect(() => {
if (!enabled) {
return
}
const textArea = ref.current
if (!textArea) {
return
}
const resizeObserver = new ResizeObserver(() => {
textArea.style.height = 'auto'
textArea.style.height = textArea.scrollHeight + 'px'
})
resizeObserver.observe(textArea)
return () => {
resizeObserver.disconnect()
}
}, [ref, enabled])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment