Skip to content

Commit

Permalink
Move resize listener to a layout effect (#305)
Browse files Browse the repository at this point in the history
* fix: replace useEffect with useLayoutEffect for React 17

`useEffect` cleanup runs since React 17 asynchronously thats why it needs to be changed
Fixes #259

* Update .changeset/clean-kiwis-boil.md

Co-authored-by: Mateusz Burzyński <mateuszburzynski@gmail.com>
  • Loading branch information
mxschmitt and Andarist committed Feb 10, 2021
1 parent 9ba98b9 commit 49d7d04
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/clean-kiwis-boil.md
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 1 addition & 1 deletion src/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
};
Expand Down
2 changes: 1 addition & 1 deletion src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,8 @@ const TextareaAutosize: React.ForwardRefRenderFunction<

if (typeof document !== 'undefined') {
React.useLayoutEffect(resizeTextarea);
useWindowResizeListener(resizeTextarea);
}
useWindowResizeListener(resizeTextarea);

return <textarea {...props} onChange={handleChange} ref={ref} />;
};
Expand Down

0 comments on commit 49d7d04

Please sign in to comment.