skip to Main Content

What is the difference between Navigate component and UseNavigate hook in react router dom? What are the specific use cases and how to decide which one to use?

I tried to navigate logged in user to a different page. Worked with useNavigate but not with Navigate.

2

Answers


  1. What is the difference between Navigate component and useNavigate hook
    in React-Router-DOM?

    One is a React component and must be rendered as JSX to the DOM

    return <Navigate to="/somePath" />;
    

    the other is a React hook that can only be called in a React component or custom React hook

    const navigate = useNavigate();
    
    const clickHandler = () => navigate("/somePath");
    

    What are the specific use cases and how to decide which one to use?

    The basic difference between them is the difference between Declarative and Imperative programming. Use the Navigate component when rendering JSX to declaratively say what you want the code to do and React will handle the flow, e.g. you are declaring what you want the behavior to be but are not implementing it directly. Use the useNavigate hook to access the navigate function and imperatively say what you want the code to do.

    I tried to navigate logged in user to a different page. Worked with
    useNavigate but not with Navigate.

    You can not return JSX from a callback as it isn’t part of the JSX that is returned when the component renders.

    This doesn’t work because <Navigate to="/somePath" /> isn’t rendered to have any effect.

    ...
    
    const clickHandler = () => <Navigate to="/somePath" />;
    
    ...
    
    return (
      ...
      <button type="button" onClick={clickHandler}>Navigate</button>
      ...
    );
    

    This works because navigate is called imperatively to issue the navigation action.

    ...
    const navigate = useNavigate();
    
    const clickHandler = () => navigate("/somePath");
    
    ...
    
    return (
      ...
      <button type="button" onClick={clickHandler}>Navigate</button>
      ...
    );
    
    Login or Signup to reply.
    1. Navigate using inside component like
        <Navigate to="/home" />
    
    1. UseNavigate using inside function like
        const navigate = UseNavigate();
        const go() = {
          navigate('/home');
        }
        <button onClick = {go} />     
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search