목차
HOC vs HOF
HOC (Higher Order Component)
- 특정 컴포넌트를 실행하기 전에 상위 컴포넌트를 먼저 실행시켜주는 방식
- JavaScript의 클로저 함수를 이용함
- HOC을 하나 만들어서 로그인이 필요한 컴포넌트 앞에 HOC만 붙여주면 간단하게 권한처리를 완료함
- 다른 컴포넌트와 함께 실행되는 고차 컴포넌트이므로 이름 앞에 with를 붙여줌
- ex) withAuth, withApollo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const withAuth = (Component) => (props) => { | |
const router = useRouter(); | |
const { accessToken } = useContext(GlobalContext); | |
// 토큰체크 | |
useEffect(() => { | |
if (!accessToken) router.push("/login"); | |
}, []); | |
if (!accessToken) return <></>; | |
return <Component {...props} />; | |
}; | |
export default withAuth; | |
const UserPage = (props) => { | |
return <div>회원 페이지입니다.</div>; | |
}; | |
export default withAuth(UserPage); |
HOC 장점
- event.target.id를 사용하지 않아 코드가 간략해짐
- material-ui, ant-desing 등의 컴포넌트를 이용하면 id 값이 날라가는 현상을 막을 수 있음
- id는 전체 태그에서 고유해야하기 때문에, id가 남용되면 대규모 서비스에서 문제가 야기될 수 있지만 이를 방지할 수 있음
HOF (Higher Order Function)
- HOC와 비슷하지만 HOC는 Component 형태, HOF는 Function 형태의 차이가 있음
┌ Component 형태 : JSX를 return 한다
└ Functino 형태 : JSX를 return 안 함
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useRouter } from "next/router"; | |
import { useEffect } from "react"; | |
export const withAuth = (Component) => (props) => { | |
const router = useRouter(); | |
useEffect(() => { | |
const accessTokenItem = window.localStorage.getItem("accessToken"); | |
console.log("withAuth", accessTokenItem); | |
if (!accessTokenItem) { | |
alert("로그인을 먼저 해주세요"); | |
router.push("./login"); | |
} | |
}, []); | |
return <Component {...props} />; | |
}; |
└ 공통컴포넌트 폴더에 파일 withAuth 생성
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { gql, useQuery } from "@apollo/client"; | |
import { withAuth } from "../../../src/components/commons/hocs/withAuth"; | |
const LogInfoPage = () => { | |
const { data } = useQuery(FETCH_USER_LOGGED_IN); | |
return <div>로그인한 유저 정보 페이지</div> | |
}; | |
export default withAuth(LogInfoPage); |
└ withAuth가 실행되고 LogInfoPage가 실행되어 로그인 상태인 유저만 페이지에 들어갈 수 있음
'React > 2022-上' 카테고리의 다른 글
Recursive Functions (0) | 2022.04.24 |
---|---|
React Currying (0) | 2022.04.18 |
JS Closure (0) | 2022.04.18 |
권한 분기 (0) | 2022.04.18 |
Cookie, Session, Local Storage (0) | 2022.04.18 |