react-router: [Bug]: Invalid useEffect warning

What version of React Router are you using?

6.3.0

Steps to Reproduce

Run the following code:

function Child(props) {
  useEffect(() => {
    props.wrappedNavigate('./otherRoute')
  }, []);
  return <></>
}

function Parent() {
  const navigate = useNavigate();
  const wrappedNavigate = (to) => {
    navigate(to);
  }
  
  return <Child wrappedNavigate={wrappedNavigate} />
}

Expected Behavior

Navigate works and performs navigation.

Actual Behavior

You should call navigate() in a React.useEffect(), not when your component is first rendered. is logged into the console. This is due to the fact that the useEffect of the Child component is executed before the useEffect of the useNavigate, which causes invalid protection on navigation.

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 39 (17 by maintainers)

Commits related to this issue

Most upvoted comments

😆 @ryanflorence this is not resolved 🤷🏻‍♂️

I’m not sure why we did that check, looking into it.

@joshribakoff-sm I was able to reproduce and resolve the issues in theory, but there’s a hold up getting approval to sign their CLA, I’ve been asked for a corporate CLA instead of an individual CLA but one hasn’t been provided. I’ve got the open pull request below although it looks like it has merge conflicts now.

https://github.com/remix-run/react-router/pull/8929

I’ll go back to our open source community and see if I can get approval to do an individual CLA contribution. It’s necessary because I put this fix together with company time, because we experienced the same issue.

I am having an issue with this too. But mostly when using React 18 / react-testing-library v13.3 for unit testing via a memory router. The same unit test worked fine in React 17 / testing library 12.x. Only after an upgrade seeing these issues.

My code is very similar to the one mentioned here https://github.com/remix-run/react-router/issues/8809#issuecomment-1152585637. Only difference is I am calling the navigate function onClick of a button or a link. Navigation fails to happen because of this line if (!activeRef.current) return; because for some reason (useEffects not running in the intended order that react-router expects) at the time of execution activeRef.current is false.

We wrap navigate in Remix and don’t have this problem. Can you make a reproduction in codesandbox or something?

Also, can somebody make a codesandbox that reproduces this issue? I can’t reproduce it.