개발관련/리액트

[React] Hoc 와 render 속성 값 사용 비교

개발자 Dane 2022. 9. 14. 17:01
반응형

Hoc vs Render 속성 값

컴포넌트에 공통적으로 사용되는 로직을 재사용 가능하도록 구현하는 방법에는 Hoc 와 Prop render 를 사용하는 2가지 방법이 있다.

1. 컴포넌트 내부 일부에서 적용하는 경우

HOC

현재 컴포넌트의 전체에 적용

//HOC
//로그인시에만 렌더링하는 HOC
const WithIsLogin =  WrappedComponent =>
	class WithIsLogin extends Component {
		state = {
			isLogin : false
		}
		checkIsLogin = ()=> {
			/***/
		}
		componentDidMount(){
			this.setState({ isLogin : this.checkIsLogin() })
		}
		render(){
			if(this.state.isLogin){
				return <WrappedComponent {...this.props}/>
			}else{
				return "로그인이필요합니다."
			}
		}
	}

//사용
class ExampleComponent extends Component {
	render(){
		return (
			<div>로그인하면 보임</div>
		)
	}
}

export default WithIsLogin(ExampleComponent)

현재 컴포넌트의 일부 render 를 제어 하는 경우

//IsLogin.js
const IsLogin = ({children})=>children
export default withIsLogin(IsLogin)

//사용
class ExampleComponent extends Component {
	render(){
		return (
			<IsLogin>
				<div>로그인하면 보임</div>
			</IsLogin>
			<div>로그인상관 없이 항상 rendering </div>
		)
	}
}

export default ExampleComponent
  • wrapper 컴포넌트를 만들어야 한다.

Props Render

//IsLogin.js
class IsLogin extends Component {
	state = {
		isLogin : false
	}
	checkIsLogin = ()=> {
		/***/
	}
	componentDidMount(){
		this.setState({ isLogin : this.checkIsLogin() })
	}
	render(){
		if(this.state.isLogin){
			return this.props.children()
		}else{
			return "로그인이필요합니다."
		}
	}

//사용
class ExampleComponent extends Component {
	render(){
		return (
			<IsLogin>
				<div>로그인하면 보임</div>
			</IsLogin>
			<div>로그인상관 없이 항상 rendering </div>
		)
	}
}

export default ExampleComponent
반응형