reactjsreact-router

Navigate vs UseNavigate in react router dom


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.


Solution

  • 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>
      ...
    );