'Material-UI: Too many re-renders. The layout is unstable. TextareaAutosize limits the number of renders to prevent an infinite loop
I have the following piece of code:
export function MyTextField({ onChange, defaultValue }) {
return (
<TextField
defaultValue={defaultValue}
onChange={(event) => {
if (onChange) {
onChange(event.target.value);
} else {
console.log("*no onChange function added*", event.target.value);
}
}}
/>
);
}
//then I use MyTextField in another component
const [recommendations, setRecommendations] = useState(
(appointment.recommendations) || ""
)
console.log(recommendations) // logs as expected with every onChange
<MyTextField
defaultValue={recommendations}
onChange={setRecommendations}
/>
After some 10 or more 'onChange' happen, I get this error on the console:
Material-UI: Too many re-renders. The layout is unstable.
TextareaAutosize limits the number of renders to prevent an infinite loop.
I've read other SO questions suggesting I use a arrow function but I don't think I did this right because the error persists.
Solution 1:[1]
I found the answer to this actually wasn't anything to do with your code actually doing updates. It's MUI not being able to find stable dimensions for the TextField when using the multiline parameter, as there are too many variables.
In my case it was a TextField with pretty much infinite space around it; MUI didn't know whether to make the input wide or tall!
So I fixed it by using the fullWidth parameter; so it was effectively constrained in a direction.
I hope that helps someone :)
Solution 2:[2]
You face an issue with controlled/uncontrolled components. Read this article for more details. You should change 'defaultValue' to simply 'value' to make it work properly.
export function MyTextField({ onChange, value }) {
return (
<TextField
value={value}
onChange={(event) => {
if (onChange) {
onChange(event.target.value);
} else {
console.log("*no onChange function added*", event.target.value);
}
}}
/>
);
}
const [recommendations, setRecommendations] = useState(
(appointment.recommendations) || "defaultValueYouNeed"
)
<MyTextField
value={recommendations}
onChange={setRecommendations}
/>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Jamie Robinson |
Solution 2 |