The useNavigate hook is a hook that returns a navigate function that can be used to navigate to a new location. This includes changes to the pathname, search params, hash, and location state.
The useNavigate hook accepts a single argument, an options object.
The navigate function is a function that can be used to navigate to a new location.
The navigate function accepts a single argument, an options object.
import { useNavigate } from '@tanstack/react-router'
function PostsPage() {
const navigate = useNavigate({ from: '/posts' })
const handleClick = () => navigate({ search: { page: 2 } })
// ...
}
function Component() {
const navigate = useNavigate()
return (
<div>
<button
onClick={() =>
navigate({
to: '/posts',
})
}
>
Posts
</button>
<button
onClick={() =>
navigate({
to: '/posts',
search: { page: 2 },
})
}
>
Posts (Page 2)
</button>
<button
onClick={() =>
navigate({
to: '/posts',
hash: 'my-hash',
})
}
>
Posts (Hash)
</button>
<button
onClick={() =>
navigate({
to: '/posts',
state: { from: 'home' },
})
}
>
Posts (State)
</button>
</div>
)
}
import { useNavigate } from '@tanstack/react-router'
function PostsPage() {
const navigate = useNavigate({ from: '/posts' })
const handleClick = () => navigate({ search: { page: 2 } })
// ...
}
function Component() {
const navigate = useNavigate()
return (
<div>
<button
onClick={() =>
navigate({
to: '/posts',
})
}
>
Posts
</button>
<button
onClick={() =>
navigate({
to: '/posts',
search: { page: 2 },
})
}
>
Posts (Page 2)
</button>
<button
onClick={() =>
navigate({
to: '/posts',
hash: 'my-hash',
})
}
>
Posts (Hash)
</button>
<button
onClick={() =>
navigate({
to: '/posts',
state: { from: 'home' },
})
}
>
Posts (State)
</button>
</div>
)
}
Your weekly dose of JavaScript news. Delivered every Monday to over 100,000 devs, for free.