hookrouter icon indicating copy to clipboard operation
hookrouter copied to clipboard

Navigate & useRedirect : Cannot update a component from inside the function body of a different component.

Open StallionV opened this issue 5 years ago • 2 comments

React 16.3 has new warnings to warn when A React component causes side effects in other components during rendering.

e.g. when using a [state, setState], if you are using setState inside some other component it has to be wrapped inside a useEffect to ensure synchronous rendering.

This now thrown errors in console(at least in dev mode) Cannot update a component from inside the function body of a different component. when we are using useRedirect and navigate from hook routers. But there may be other places and APIs, where this scenario would as well be happening

The library needs to be relooked to identify any places where this is happening and start wrapping them in useEffect where needed.

Work arounds For now to make this work wrap the navigate call with a dummy setTImeout this will make the call synchronous and stop the warning Previous navigate("/")

New

setTimeout(() => {
    navigate("/")
 }, 0)

This won't work for useRedirects so the temporary option is to replace them with navigate

StallionV avatar Mar 02 '20 23:03 StallionV

@Paratron I saw the note about library being rewritten https://github.com/Paratron/hookrouter/issues/112 If so please consider looking at issues like these to make it more robust. Thanks again for the library in the first place

StallionV avatar Mar 26 '20 18:03 StallionV

The error I get is this:

index.js:1 Warning: Cannot update a component (App) while rendering a different component (Component). To locate the bad setState() call inside Component, follow the stack trace as described in https://reactjs.org/link/setstate-in-render

It's unfortunate that this problem has persisted unfixed for so long.

forresthopkinsa avatar Jul 29 '21 04:07 forresthopkinsa