diff --git a/.changeset/clean-kiwis-boil.md b/.changeset/clean-kiwis-boil.md new file mode 100644 index 00000000..63b0b543 --- /dev/null +++ b/.changeset/clean-kiwis-boil.md @@ -0,0 +1,5 @@ +--- +'react-textarea-autosize': patch +--- + +Moved internal `'resize'` listener to the layout effect since React 17 calls cleanups of regular effects asynchronously. This ensures that we don't ever try to access the already unmounted ref in our listener. diff --git a/src/hooks.ts b/src/hooks.ts index 307012c5..0c405b30 100644 --- a/src/hooks.ts +++ b/src/hooks.ts @@ -6,7 +6,7 @@ export { default as useComposedRef } from 'use-composed-ref'; export const useWindowResizeListener = (listener: (event: UIEvent) => any) => { const latestListener = useLatest(listener); - React.useEffect(() => { + React.useLayoutEffect(() => { const handler: typeof listener = (event) => { latestListener.current(event); }; diff --git a/src/index.tsx b/src/index.tsx index 250a87ca..513f15c3 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -92,8 +92,8 @@ const TextareaAutosize: React.ForwardRefRenderFunction< if (typeof document !== 'undefined') { React.useLayoutEffect(resizeTextarea); + useWindowResizeListener(resizeTextarea); } - useWindowResizeListener(resizeTextarea); return