본문 바로가기
Frontend/React

[React] useNavigate(), useLocation()

by 민두이 2023. 2. 16.
728x90
반응형

useNavigate()

특정 경로로 가게 해주는 훅

첫번째 인자에 경로를 넣어주고 두번째 인자에는 해당 경로로 보내고자하는 정보를 넣어줄 수 있다

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

function VideoCard({ video }) {
    const navigate = useNavigate();

    return (
    ///videos/watch/${id} 경로에 state로 video 데이터를 보내줌
        <li onClick={() => navigate(`/videos/watch/${id}`, {state:{video}})}>
        </li>

 

useLocation()

useNavigate의 두번 째 인자를 통해서 전달해준 정보를 갖고오는 방법

import React from 'react';
import { useLocation } from 'react-router-dom';

export default function VideoDetail() {

    const {state :{video}} = useLocation();
    console.log(video);
    
     return (
        <div>
            VIDEO DETAILS : 
        </div>
    );
    }

 

 

 

https://reactrouter.com/en/main/hooks/use-navigate

 

useNavigate v6.8.1

useNavigate It's usually better to use redirect in loaders and actions than this hook The useNavigate hook returns a function that lets you navigate programmatically, for example in an effect: import { useNavigate } from "react-router-dom"; function useLog

reactrouter.com

 

https://reactrouter.com/en/main/hooks/use-location

 

useLocation v6.8.1

useLocation Type declarationdeclare function useLocation(): Location; interface Location extends Path { state: unknown; key: Key; } This hook returns the current location object. This can be useful if you'd like to perform some side effect whenever the cur

reactrouter.com

 

728x90