관리 메뉴

Silver Library (Archived)

useLocation, react-router-dom 본문

Face the fear, build the future/Revision Sector

useLocation, react-router-dom

Chesed Kim 2022. 11. 11. 19:04
반응형

useLocation, 이건 query parameter 를 받아오는 용도로 알려져 있는데 한번 간략히 상기삼아 기록해보겠습니다.

 

useLocation? 

This hook returns the current location object. This can be useful if you'd like to perform some side effect whenever the current location changes.

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

function App() {
  let location = useLocation();

  React.useEffect(() => {
    // Google Analytics
    ga('send', 'pageview');
  }, [location]);

  return (
    // ...
  );
}

useLocation is one of the very useful hooks in react-router-dom library when it comes to URL tracking. We can use it easily in our applications for making decisions based on the URL the app has been routed to.

 

The useLocation hook returns the location object from the current URL, which includes the following:

  • pathname: This is the path of the URL.
  • search: This is the query string (?) included in the URL.
  • hash: This is the result of the hash fragment (#) from the URL.

Example

 

How to use the useLocation hook in React

Contributor: Nasreen

www.educative.io

Below is a small code(see the link above) snippet showing how we can extract the pathname and search parameter from useLocation hook.

 

The code below contains a "Click Me" button, which navigates the user to the URL, 'https:localhost:3000/products/school?name=bags'.

 

For example, if I have a URL, http://localhost:3000/products/school/?name=bags, the result from the useLocation object will be the following:

  • pathname: /products/school
  • Query parameter: bags

그럼 다른 사례는?

이렇게 활용 해 볼 수 있었습니다.

참고 및 영감이 되었던 것 중 하나(한글): 

 

[React] useLocation 사용

baGETTT 프로젝트를 진행하면서 결제완료 페이지 구현을 담당했다.장바구니 페이지에서 결제하기 버튼을 누르면,구매 정보 데이터를 보여주는 결제 완료 페이지로 이동을 하게 된다.그 과정에서

velog.io

그래서 이걸 찾다 보니 알게된 게, 'useLocation 으로 정말 toggle button 이 절대적으로 반응하게 끔 설계' 하는 게 가능한 기능이 있었습니다. 한마디로 '링크가 바뀌면, 무조건 지정해 둔 대로 작동해!' 라고 구성하는 방식이었습니다. 이걸 몰라서 같은 목적을 가진 사이드 프로젝트를 4번이나 눈물을 머금고 포기하고 계속 만들어 봤던 걸 생각하면...

 

아래와 같이 말이죠.

import { Link, useLocation } from "react-router-dom";
import React, { useEffect, useState } from "react";

function Navbar() {
  const [expandNavbar, setExpandNavbar] = useState(false);

  const location = useLocation();

  useEffect(() => {
    setExpandNavbar(false);
  }, [location]);

  return (
    <div className="navbar" id={expandNavbar ? "open" : "close"}>
      <div className="toggleButton">
        {/* toggle button for mobile */}
        <button
          onClick={() => {
            setExpandNavbar((prev) => !prev);
          }}
        >
        </button>
      </div>
      ...

추가 주석:

useLocation. The useLocation hook returns the location object that represents the current URL. You can think about it like a useState that returns a new location whenever the URL changes.
 
This could be really useful e.g. in a situation where you would like to trigger a new “page view” event using your web analytics tool whenever a new page loads(...)

 

여담.

결국 이건 데이터 통신 관련 사전 지식이 있었더라면, 단번에 떠올랐을 감(sense)일 것 같다는 생각이 들었습니다. 그 마저도 네트워크 용어 관련 서적을 읽었던 경험이 있었기에, 저도 button 하고 useLocation 을 활용 한 코드를 봤을 때, 아 그런 목적으로 쓰는구나! 라는 걸 알았으니까요.

 

요약:

useLocation hook는, 현재 페이지에 대한 정보를 알려줍니다.

이걸 활용해서, (예: location.state.result.package) current page 를 state 로 passing 해서 활용 가능.

이렇게 useLocation 을 활용해서 결제 후, 장바구니 내용물을 표시하게 할 수도 있고.

 

아니면 useLocation 을 toggle button 에 의해 반응하여 작동된 것이, 다른 페이지로 이동하여 useLocation (location) 이 변경되는 걸 감지하는 순간, 'useEffect' 내부에 지정 한 구성대로 행동하게 하는 '일종의 trigger 장치 역할' 을 하도록 하는 용도, 같이 사용 할 수 있었다고 봅니다.