17

Can anyone please explain the differences between {Link} and {useNavigate} from 'react-router-dom'? I am new to React and I see both {Link} and {useNavigate} are used to navigate through routes. So how are they different?

Tanh
  • 229
  • 1
  • 3
  • 6

4 Answers4

15

The difference between the Link (and NavLink and Navigate) components and the navigate function returned by the useNavigate hook is effectively the same difference between Declarative and Imperative programming.

Declarative vs Imperative Programming

Declarative programming is a paradigm describing WHAT the program does, without explicitly specifying its control flow. Imperative programming is a paradigm describing HOW the program should do something by explicitly specifying each instruction (or statement) step by step, which mutate the program's state.

  • Imperative programming – focuses on how to execute, defines control flow as statements that change a program state.
  • Declarative programming – focuses on what to execute, defines program logic, but not detailed control flow.

With the Link (and NavLink and Navigate) components you effectively declare, or defer, what you want to happen, and the component handles getting it done and executing it. These are declarative navigation actions.

Example declarative link:

<Link to="page">Page</Link>

It only specifies the target it wants to get to, but doesn't explain how to get there.

With the navigate function you are explicitly issuing a command to navigate now, immediately. This is an imperative action.

Example imperative link:

<Link
  to="page"
  onClick={(e) => {
    e.preventDefault();
    navigate("page");
  }}
>
  Page
</Link>

This version explicitly explains that if clicked on run this specific logic to navigate to this page.

Note also that Link is a React component and as such it must be rendered into the DOM as part of the return from a React component, whereas the navigate function is a function and can be used in callbacks.

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • 1
    Can you please let me know about some use cases of each one of these? – Emad Baqeri Apr 14 '22 at 06:22
  • @EmadBaqeri Are you looking for any specific examples? Anything that isn't already covered in the [API reference docs](https://reactrouter.com/docs/en/v6/api)? – Drew Reese Apr 14 '22 at 06:24
  • 1
    Yes, that would be great. But the thing that I'm looking for is to see this explanation which is really good in a real world example or some examples – Emad Baqeri Apr 14 '22 at 06:26
  • 5
    @EmadBaqeri Use the `Link`/`NavLink` components to allow the user to interact with the page and navigate. `Navigate` component to more or less redirect (*it is the successor to v5's `Redirect` component*), and use the `navigate` function in callbacks, like a `form` element's `onSubmit` handler, or after fetching data in an `useEffect` hook. – Drew Reese Apr 14 '22 at 06:32
4

Link is JSX element, it is replace <a>, so it can navigate between route when it clicked without refresh the page.

<Link to='/about'>To About Page</Link>

useNavigate is router hook. Same as Link but it can navigate between route programatically, like onSubmit, it will redirect to anoother page

  let navigate = useNavigate();

  async function handleSubmit(event) {
    event.preventDefault();
    await submitForm(event.target);
    navigate("/success", { replace: true });
  }

  return <form onSubmit={handleSubmit}>{/* ... */}</form>;
Kofusu
  • 164
  • 1
  • 10
3

Link and NavLink are mostly same thing.We use both of them to route pages.But the difference is when we use NavLink we get some advantages like we can design our navigation with active state.Because the NavLink component provides a active class inside it.So we can design our navigation when it is active and we can keep track the active pages.

useNavigate is a hook which returns a function to navigate.But to do this we need to call a navigate function and it declares that how it will work.

0

Let's say you have some needs to render the some page after checking something (e.g. you have criteria to check whether user have login before or not, so first you check the session of webpage if session is valid or present then then you redirect to user main page otherwise you told that user is log out.) that's time Link and useNavigate use cases shining very much. code for above thing--->

index.js

root.render(
  <BrowserRouter>
    <App/>
</BrowserRouter>
);

App.js

const navigate=useNavigate()  //remember useNavigate only valid inside
    useEffect(()=>{          // BrowserRouter that's why I wrap App.js 
                            //  by BrowserRouter in index.js
        const key=localStorage.getItem('key');
        console.log(key);
        if(key===undefined){
            navigate('/')
        }else{
           navigate('/list')
        }
    },[1])
    return  <Routes>
    <Route path="/" element={<Authentication/>}/>
    <Route path="/list" element={<List/>}/>
    </Routes>

If I use Link despite of useNavigate then Browser will not complain but it's not working under the hood. Because Link is only valid till if you include inside webpage(DOM) like anchor or a tag inside html page because Link is same as a tag. But useNavigate is a function or hook what's use anywhere in your code. Because useNavigate not need to add inside DOM.