It can be solved by dependency
Infinite loops can be fixed by properly managing useeffect (callback, dependencies)
dependency parameters.
Because we want count
to increase when the value changes, we can simply use value
as a dependency for side effects.
import { useEffect, useState } from 'react';
function CountInputChanges() {
const [value, setValue] = useState('');
const [count, setCount] = useState(-1);
useEffect(() => setCount(count + 1), [value]);
const onChange = ({ target }) => setValue(target.value);
return (
<div>
<input type="text" value={value} onChange={onChange} />
<div>Number of changes: {count}</div>
</div>
);
}
Add [value]
as the dependency of useeffect
, so that the count status variable will be updated only when [value]
changes. This solves the infinite loop.
Similar Posts:
- [Solved] java.lang.Long cannot be cast to java.lang.Integer
- How to Use awk to Analyze Nginx Log
- [Vue warn]: You may have an infinite update loop in a component render function
- Each child in an array or iterator should have a unique “key” prop. Check the render method of `Tabl
- How to Solve Const variable assignment Error
- [Solved] Operator overload must take either zero or one argument error
- Solution to the problem of “TypeError: Assignment to constant variable”
- [Solved] Computed property “xxxx” was assigned to but it has no setter
- event.srcElement And event.target The difference between