question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Infinite loop: mixing watch, useEffect and setState

See original GitHub issue

Describe the bug Not sure if this is a bug or if I’m missing something. I’m using a few Controllers to control custom components (custom inputs) and I want to detect whenever the whole form data changes so I can filter/process it.

Using watch() as a dependency of useEffect and using state inside of it causes an infinite loop.

To Reproduce

https://codesandbox.io/s/react-hook-form-infinite-loop-hx32d?file=/src/App.js

Uncomment the “setFilters()” to reproduce the infinite loop. Without it, it’s all good.

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Reactions:3
  • Comments:11 (3 by maintainers)

github_iconTop GitHub Comments

6reactions
ambewascommented, Jul 20, 2021

We’re noticing a similar problem - we’re using watch to access a value and pickup changes to it. The value is from react-select and is thus an object ( { value: 'foo', label: 'bar'} ).

We’re having to set some local state using useState depending on which element was selected. So we’ve got a hook doing something like this:

const { localState, setLocalState } = useState();
const watchedObject = watch('somePath');

useEffect(() => {
  setLocalState(watchedObject);
}, [watchedObject])

in the browser, this runs fine, persumably because watchedObject is the same reference everytime – but for some reason in our specs, this triggers an infinite loop - (to specify our use case: we’re changing a part of the form that is rendered based on localState - and we’re having to put it in localState instead of relying on watch alone, because we’re using the value in localState to change the schema passed to useForm. )

We’ve solved this with comparing localState with watchedObject – but it’s kinda not ideal to write code just to make specs pass.

const { localState, setLocalState } = useState();
const watchedObject = watch('somePath');

useEffect(() => {
  if (isNotTheSameByDeepCompare(localState, watchedObject)) {
    setLocalState(watchedObject);
  }
}, [watchedObject])

Any advice on how to improve this workaround with an official solution would be much appreciated 👍

3reactions
hosamre94commented, Jul 8, 2021

Watched values doesn’t gets memories, that’s the issue here. I wouldn’t use watch return value as useEffect dep.

for me i don’t think this is the case, the useEffect works fine it’s only got triggered whenever a value inside the form is changed , but the problem is each setValue inside the useEffect is triggering the watch again which call the setValue again so on and so forth i have infinite loop

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to Solve the Infinite Loop of React.useEffect()
1.1 Fixing dependencies ... The infinite loop is fixed by correct management of the useEffect(callback, dependencies) dependencies argument.
Read more >
How to solve the React useEffect Hook's infinite loop patterns
To get rid of your infinite loop, simply use an empty dependency array like so: const [count, setCount] = useState(0); //only update the...
Read more >
Fix the "Maximum Update Depth Exceeded" Error in React
One of which is when you accidentally cause an infinite render loop, often resulting in the cryptic “maximum update depth exceeded” error.
Read more >
uncaught error too many re-renders. react limits the number of ...
The reason for the infinite loop is because something (most likely setState ) in the event callback is triggering a re-render.
Read more >
Preventing loop inside useEffect with setState - Stack Overflow
useEffect (() => { fetch(url,({value, ...data}) => { // this is callback function when data fetched setData(data); setValue(value); // <- this ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found