Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[TextareaAutosize] prevent redundant state updates #32783

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions packages/mui-base/src/TextareaAutosize/TextareaAutosize.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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;
Expand Down Expand Up @@ -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.
Expand Down