Skip to content
Advertisement

Updating State in React Component causing it to get unmounted

I have a component where-in I need to fetch some data and render it. The component gets rendered initially. The problem I’m facing is when the handler function switchDocumentType is called after clicking the button for a particular type, the whole component gets unmounted/un-rendered.

While debugging on my own I found this happens after setDocumentType is run inside event handler function. What is wrong in the below code snippet that could possibly cause this issue? I can see the useEffect is not going in infinite-loop as well.

Code snippet:

JavaScript

Advertisement

Answer

Not sure why but placing debuggers before state update causes this issue, not only for this component, but for all the other components I tried with. Seems to be an issue either with debugger or React. Removing debuggers solved the issue.

Also, now I’m returning a cleanup function inside useEffect as pointed out in some stack-overflow posts. I also refactored the code as suggested by @iaq and @sheepiiHD to follow React best practices.

Updated code:

JavaScript
Advertisement