From 99cef6ddae4eb607a062f05ffd15f2b3cc3fabf3 Mon Sep 17 00:00:00 2001 From: Yama-Tomo Date: Mon, 16 May 2022 15:53:22 +0900 Subject: [PATCH] prevent redundant state updates --- .../src/TextareaAutosize/TextareaAutosize.js | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/packages/mui-base/src/TextareaAutosize/TextareaAutosize.js b/packages/mui-base/src/TextareaAutosize/TextareaAutosize.js index f3e4cdbc222e1e..36696cf33a7781 100644 --- a/packages/mui-base/src/TextareaAutosize/TextareaAutosize.js +++ b/packages/mui-base/src/TextareaAutosize/TextareaAutosize.js @@ -27,6 +27,18 @@ const styles = { }, }; +const isNeedUpdateState = (heightStateRef, { overflow, outerHeightStyle }) => { + if ( + heightStateRef.current.overflow !== overflow || + heightStateRef.current.outerHeightStyle !== outerHeightStyle + ) { + heightStateRef.current = { overflow, outerHeightStyle }; + return true; + } + + return false; +}; + const TextareaAutosize = React.forwardRef(function TextareaAutosize(props, ref) { const { onChange, maxRows, minRows = 1, style, value, ...other } = props; @@ -36,6 +48,7 @@ const TextareaAutosize = React.forwardRef(function TextareaAutosize(props, ref) const shadowRef = React.useRef(null); const renders = React.useRef(0); const [state, setState] = React.useState({}); + const heightStateRef = React.useRef({}); const syncHeight = React.useCallback(() => { const input = inputRef.current; @@ -86,6 +99,10 @@ const TextareaAutosize = React.forwardRef(function TextareaAutosize(props, ref) const outerHeightStyle = outerHeight + (boxSizing === 'border-box' ? padding + border : 0); const overflow = Math.abs(outerHeight - innerHeight) <= 1; + if (!isNeedUpdateState(heightStateRef, { overflow, outerHeightStyle })) { + return; + } + setState((prevState) => { // Need a large enough difference to update the height. // This prevents infinite rendering loop.