[ useLocation ] 현재 위치는 어디인가?

정제우·2023년 5월 17일
0

ReactHook

목록 보기
1/2

React를 사용하다가 위치에 관련된 사항들을 추가하고 싶다면, useLocation 이라는 ReactHook을 사용하면 된다.

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

function MyComponent() {
  const location = useLocation();

  console.log(location.pathname); // 현재 경로
  console.log(location.search); // 현재 쿼리 매개변수

  return (
    <div>
    </div>
  );
}

location.pathname 으로 현재경로의 정보를 가져올 수 있고

  if (
    !isLogin &&
    (location.pathname === '/profile')
  ) {
    return <Navigate to="/account/login" />;
  }

위코드는 isLogin 상태가 false 일경우 /profile 경로에 접근하면 Login 경로로 보내주기위해 작성한 코드이다.

location.search 으로 현재 쿼리 매개변수의 정보를 가져올 수 있다.

  const queryParams = new URLSearchParams(location.search);
  const userId = queryParams.get('id');
  const [userProfile, setUserProfile] = useState(null);
  useEffect(() => {
    // userId를 사용하여 사용자 프로필 데이터 가져오기
    // 예를 들어, API 호출 등의 비동기 작업 수행
    fetchUserProfile(userId)
      .then(data => setUserProfile(data))
      .catch(error => console.log(error));
  }, [userId]);

useEffect를 이용하여 쿼리 파라미터 중에 userId가 바뀔때마다 해당 userId로 api를 요청하여 업데이트 되도록 작성한 코드이다.


결론

단독적으로 사용되는 경우는 드무나, 다양한 hook과 함께 사용하면 정말 편리한 React Hook이 되겠다.

profile
안녕하세요 FE 취준생 정제우 입니다. 면접과 TIL 위주로 작성하는 벨로그에 오신것을 환영합니다.

0개의 댓글