-
728x90
useLocation과 useNavigation은 React Router에서 제공하는 훅으로 라우팅 관련 기능을 사용할 때 유용하다.
1. useNavigation
const navigate = useNavigate(); const handleSearch = () => { navigate("/hotels", { state: { destination, date, options } }); };
useNavigation은 페이지를 이동하면서 값을 전달하고 URL경로를 변경하는데 사용한다.
navigate 첫번째 인자로 이동할 경로, 두번째 인자로 state객체를 전달한다.
handleSearch() 함수가 호출되어 /hotels 경로에 들어갈 때 state 객체를 포함해서 /hotels 페이지에 전달할 수 있다.
2. useLocation
const location = useLocation(); const [destination, setDestination] = useState(location.state.destination); const [date, setDate] = useState(location.state.date); const [options, setOptions] = useState(location.state.options);
이동된 페이지에서useLocation 훅을 사용하여 location을 콘솔에 찍어보면 hash, pathname,search, state같은 location 객체 속성 정보가 나오는걸 확인할 수 있으며, 여기서 state객체 값을 가져올 수 있다.
참고로 navigate함수를 Link 컴포넌트로 대체할 수 있다.
<Link to={{ pathname: '/hotels', state: { destination, date, options } }}>
마찬가지로 다음페이지에서 location으로 pathname URL 경로부분과 state 객체를 가져올 수 있다.
'React, Next' 카테고리의 다른 글
[React] 리액트로 OpenWeatherMap API 사용하기 (0) 2023.06.18 [React] Context API와 useReducer로 상태관리하기 (0) 2023.05.31 [React] 커스텀 훅(Custom Hooks) 만들기 (0) 2023.05.28 [React] onKeyDown, onKeyUp 한글 입력 처리 문제 (0) 2023.05.23 [Redux] Redux란? (0) 2023.05.18 댓글