advanced technique in React for reusing component logic
not part of the React API
a pattern that emerges from React’s compositional nature.
HOC = function(컴포넌트) { return 새로운 컴포넌트; }
<컴포넌트>를 인자로 받아 <새로운 컴포넌트>를 리턴하는 함수
props ⇒ component ⇒ UI
component ⇒ HOC ⇒ NEW component
보통 with 가 붙은 함수가 HOC 인 경우가 많다.
export default withRouter(LoginButton);
사용하는 법
- Use HOCs For Cross-Cutting Concerns
- Don’t Mutate the Original Component. Use Composition.
- Pass Unrelated Props Through to the Wrapped Component
- Maximizing Composability
- Wrap the Display Name for Easy Debugging
주의할 점
- Don’t Use HOCs Inside the render Method
- Static Methods Must Be Copied Over
- Refs Aren’t Passed Through (feat. React.forwardRef)
npx create-react-app controlled-uncontrolled-ex
// src/components/Components/ControlledComponent.jsx
import React from 'react';
class ControlledComponent extends React.Component {
state = {
value : '',
};
render(){
const { value } = this.state;
return (
<div>
<input value={ value } onChange={this.change} />
<button onClick={this.click}>전송</button>
</div>
)
}
change = (e) => {
// console.log(e.target.value);
this.setState( {value: e.target.value });
}
click = () => {
console.log(this.state.value);
}
}
export default ControlledComponent;
// src/components/Components/UncontrolledComponent.jsx
import React from 'react';
class UncontrolledComponent extends React.Component {
inputRef = React.createRef();
render(){
console.log("initial render", this.inputRef);
return (
<div>
{/* <input id="my-input"/> */}
<input ref={this.inputRef} />
<button onClick={this.click}>전송</button>
</div>
);
}
componentDidMount(){
console.log("componentDidMount", this.inputRef);
}
click = () => {
// input 엘리먼트의 현재 상태 값(value)를 꺼내서 전송한다.
// const input = document.querySelector('#my-input')
// console.log(input.value); 직접 value 를 꺼내오는 것은 지양!
console.log(this.inputRef.current.value);
};
}
export default UncontrolledComponent;
// src/components/Components/UncontrolledComponent.jsx
import React from 'react';
class UncontrolledComponent extends React.Component {
inputRef = React.createRef();
render(){
console.log("initial render", this.inputRef);
return (
<div>
{/* <input id="my-input"/> */}
<input ref={this.inputRef} />
<button onClick={this.click}>전송</button>
</div>
);
}
componentDidMount(){
console.log("componentDidMount", this.inputRef);
}
click = () => {
// input 엘리먼트의 현재 상태 값(value)를 꺼내서 전송한다.
// const input = document.querySelector('#my-input')
// console.log(input.value); 직접 value 를 꺼내오는 것은 지양!
console.log(this.inputRef.current.value);
};
}
export default UncontrolledComponent;