1

I came back to react world after a few years. And things certainly have changed for good. I'm using MemoryRouter for my app. And I can navigate fine by using Link. But useNaviate hook is not working as expected. It does nothing on the page. Could you please help me here? Here is my code:

Router:

<MemoryRouter>
  <Routes>
    <Route path="/" element={<Home />} />
    <Route path="/dashboard" element={<Dashboard />} />
  </Routes>
</MemoryRouter>

Here is how I'm trying the navigation:

function Home() {
  // demo purpose
  const navigate = useNavigate()
  
  navigate('/dashboard')
}

I'm not sure if I'm using it right, or if I need to do something else here.

2
  • Errors in thee console? Commented Jan 5, 2023 at 11:54
  • 2
    NVM. Found the issue. navigate should either be an event, or should be in useEffect. Commented Jan 5, 2023 at 11:57

3 Answers 3

1

The code is calling navigate as an unintentional side-effect directly in the function component body.

Either call navigate from a component lifecycle or callback to issue an imperative navigation action:

function Home() {
  const navigate = useNavigate()

  useEffect(() => {
    if (/* some condition */) {
      navigate('/dashboard');
    }
  }, [/* dependencies? /*]);
  
  ...
}

Or conditionally render the Navigate component to a declarative navigation action:

function Home() {
  ...

  if (/* some condition */) {
    return <Navigate to="/dashboard" />;
  };
  
  ...
}
Sign up to request clarification or add additional context in comments.

Comments

0

The problem was that I was calling navigate directly when the component was rendering. It should either be called in an event, or it should be called in useEffect hook.

Comments

0

Make your navigate in function call or in useEffect like this:

function Home() {
// demo purpose
const navigate = useNavigate()
  useEffect(() => {
    navigate('/dashboard')
  }, []);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.