Understanding clearly page transition using libraries in React and Next.js
Tags: beginners, react, nextjs, webdev
Published: 2024-05-05 04:59:55

## Table of Contents

1. At the Beginning
2. React
   - [useNavigate](#usenavigate(don't use useHistory))
   - [Link](#link)
   - [redirect](#redirect)
3. Next.js
   - [useRouter](#userouter)
   - [Link](#link-1)
   - [redirect](#redirect-1)
4. Conclusion

## At the beginning
When studying Next.js and React, I often found myself overwhelmed by the variety of options available for handling page transitions and frustrated by the mix of old and new information. This confusion led me to write this article, aiming to clarify which methods are best to use and when.


## React
### useNavigate
`useNavigate` is one of the hooks of React Router. React Router is an essential tool for managing navigation within React applications.
When you want to use React Router, you can install it like this.

```React
npm install react-router-dom
```
`useNavigate` simplifies the navigation code **by providing a single function**. And also it is used in event handlers and asynchronous processing.
Here is an example.

```React
import { useNavigate } from 'react-router-dom';

const MyComponent = () => {
  const navigate = useNavigate();

  const handleClick = () => {
    navigate('/about');
  };

  return (
    // JSX content
  );
};
```

> `useHistory` is previous hooks of React Router. **Don't use it now**. Since React Router v6 is released, useNavigate is the best way to navigate in applications instead of useHistory.

## Link
The `Link` component which is one of the React Router hooks is used **to create navigation links in our applications**. It's a similar role to the `a` tag in HTML.　When you click an `a` tag, the webpage refreshes, but **using the Link component does not cause a refresh**.
Here is an example.

```React
import { Link } from 'react-router-dom'

<Link to="/">Home</Link>
<Link to="/about">About</Link>
``` 

### redirect
The `redirect` hook is used in React Router to redirect the user to different router programmatically. When the component is rendered, it will **automatically redirect the user to the specified route**.　
The main difference compared with `useNavigate` is that redirect component **automatically redirects depending on conditions**, while useNavigate **programmatically controls navigation based on the logic** in the component.
Here is an example.
```React
import { redirect } from 'react-router-dom'

const MyComponent = async () => {
  const currentUser = await getUser()
  if (!user) {
    return redirect("/login")
  }
}
```

## Next.js
### useRouter
The `useRouter` （next/navigation） hook allows you to programmatically change routes in **App Router**. It can be used only in **client component**.

```React
'use client'
import useRouter from 'next/navigation'

const MyComponent = () => {
  const router = useRouter()
  const handleClick = () => {
    router.push('/')
  }
  return(
    <>
      <div>hoge</div>
      <div onClick={handleClick}>Home</div>
    </>
  )
}
```

> The `useRouter` （next/router） hook can be worked in **Pages Router**. Please be careful where useRouter is imported from.

### Link
A React component called `Link` is provided to do this in **client component**. It is the primary and recommended way to navigate between routes in Next.js. We can use it by importing it from **next/link**, and passing a **href** prop to the component in Next.js.
Here is an example.

```React
import Link from 'next/link'
 
const MyComponent () => {
  return (
    <ul>
      <li><Link href="/">Home</Link></li>
      <li><Link href="/about">About Us</Link></li>
    </ul>
  )
}
```
### redirect
When we want to navigation routes in **server component**, use the `redirect` function instead.
The `redirect` function allows you to redirect the user to another URL.

```React
import { redirect } from 'next/navigation'
import { getUser } from '../action/getUser'

const MyComponent () => {
  const user = await getUser()
  if (!user) {
    redirect("/login")
  }
  return (
    // JSX component
  )
}
```

## Conclusion
Writing this article helped me organize my thoughts. I hope it allows you to approach their future coding projects with a clearer understanding of the information.