Tag Archives: React.useEffect()

How to solve the infinite loop of react. Useeffect()?

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.