HOC

Higher Order Component?

  • 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 새로운 컴포넌트; }

Screenshot 2023-07-05 at 10.59.07 PM.png

Screenshot 2023-07-05 at 11.00.38 PM.png

Screenshot 2023-07-05 at 11.01.50 PM.png

withRouter()

export default withRouter(LoginButton);
import React from "react";
import { withRouter } from "react-router-dom";

const LoginButton = props => {
  console.log(props);
  function login() {
    setTimeout(() => {
      props.history.push("/");
    }, 1000);
  }
  return <button onClick={login}>로그인하기</button>;
};

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

Screenshot 2023-07-06 at 5.59.45 AM.png

주의할 점

  • Don't Use HOCs Inside the render Method
  • Static Methods Must Be Copied Over
  • Refs Aren't Passed Through

Don't Use HOCs Inside the render Method

render() {
  // A new version of EnhancedComponent is created on every render
  // EnhancedComponent1 !== EnhancedComponent2
  const EnhancedComponent = enhance(MyComponent);
  // That causes the entire subtree to unmount/remount each time!
  return <EnhancedComponent />;
}

Static Methods Must Be Copied Over

// Define a static method
WrappedComponent.staticMethod = function() {/*...*/}
// Now apply a HOC
const EnhancedComponent = enhance(WrappedComponent);

// The enhanced component has no static method
typeof EnhancedComponent.staticMethod === 'undefined' // true
function enhance(WrappedComponent) {
  class Enhance extends React.Component {/*...*/}
  // Must know exactly which method(s) to copy :(
  Enhance.staticMethod = WrappedComponent.staticMethod;
  return Enhance;
}
import hoistNonReactStatic from 'hoist-non-react-statics';
function enhance(WrappedComponent) {
  class Enhance extends React.Component {/*...*/}
  hoistNonReactStatic(Enhance, WrappedComponent);
  return Enhance;
}
// Instead of...
MyComponent.someFunction = someFunction;
export default MyComponent;

// ...export the method separately...
export { someFunction };

// ...and in the consuming module, import both
import MyComponent, { someFunction } from './MyComponent.js';

Controlled Component & Uncontrolled Component

npx create-react-app controlled-uncontrolled-example
상태를 가지고 있는 엘리먼트

  • input
  • select
  • textarea
  • ...

Element의 상태를 누가 관리 하느냐

실습

import React from 'react';

class ControlledComponent extends React.Component {
	state = { 
		value: '' 
	};

	render() {
		const { value } = this.state
		return (
			<div>
		        <input value={value}/>
		    </div>
	    );
	}
}
export default ControlledComponent;

components/Controlled.jsx


#React #FrontEnd