Higher-Order Component

Jung taeWoongยท2021๋…„ 3์›” 31์ผ
0

vue.js

๋ชฉ๋ก ๋ณด๊ธฐ
3/9
post-thumbnail

HOC(Higher-Order Component) ํŒจํ„ด

์—ฌ๋Ÿฌ ์ปดํฌ๋„ŒํŠธ ๊ฐ„ ๊ณต์œ ๋˜๋Š” ๋กœ์ง์„ ๊ด€๋ฆฌํ•˜๋Š” ๋ฐฉ๋ฒ•

  • React์—์„œ ํŒŒ์ƒ๋œ ํŒจํ„ด
  • ๊ณ ์ฐจํ•จ์ˆ˜(HOF, Higher-Order Function) ๊ธฐ๋ฐ˜์˜ ๋””์ž์ธ ํŒจํ„ด
  • ์ปดํฌ๋„ŒํŠธ๋ฅผ ์ธ์ˆ˜๋กœ ๋ฐ›์•„ ์ปดํฌ๋„ŒํŠธ๋ฅผ ๋ฆฌํ„ดํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ ์˜๋ฏธ

HOF(Higher-Order Function)

ํ•จ์ˆ˜๋ฅผ ์ธ์ž๋กœ ๋ฐ›์•„ ํ•จ์ˆ˜๋ฅผ ๋ฆฌํ„ดํ•˜๋Š” ํ•จ์ˆ˜

  • ๊ณตํ†ต์œผ๋กœ ์‚ฌ์šฉ๋˜๋Š” ๋กœ์ง์„ ํ•จ์ˆ˜์— ๋„ฃ๊ณ  ๊ฐœ๋ณ„์ ์ธ ๋กœ์ง์„ ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ๋ฐ›๋Š”๋‹ค
//Ex
function hof(individualLogic) {
	// x, y๋ฅผ ์ธ์ž๋กœ ๊ฐ€์ง€๋Š” ์ต๋ช…ํ•จ์ˆ˜๋ฅผ ๋ฆฌํ„ด
  return function(x,y) {
	// ์ธ์ž๋กœ ์ „๋‹ฌํ•œ individualLogic ํ•จ์ˆ˜ ์‹คํ–‰
    const result = individualLogic(x, y);
    //๊ณตํ†ต ๋กœ์ง ๋ถ€๋ถ„
    console.log('result:', result);
    return result;
  };
}

function add(x, y) {
  return x + y;
}

function multiply(x, y) {
  return x * y;
}

const addAndLog = hof(add); 
const multiplyAndLog = hof(multiply);

HOC ์ ์šฉํ•˜๊ธฐ

  • HOC ์ด๋ฆ„์€ with๋ผ๋Š” ์ ‘๋‘์–ด์™€ ํ•จ๊ผ prop์˜ ์ด๋ฆ„์„ ๋ถ™์ด๋Š” ๊ฒƒ์ด ๊ด€๋ก€
    - ์ด๋Ÿฐ ๋„ค์ด๋ฐ์„ ํ†ตํ•ด HOC๊ฐ€ ์‚ฌ์šฉ๋˜๋Š” ์ปดํฌ๋„ŒํŠธ์—์„œ ํ•ด๋‹น prop์˜ ์ถœ์ฒ˜๋ฅผ ๋ช…ํ™•ํ•˜๊ฒŒ ์ถ”์  ๊ฐ€๋Šฅ
  • ์ปดํฌ๋„ŒํŠธ ๊ฐ„์— ๊ณต์œ ๋˜๋Š” ์ฝ”๋“œ ์žฌ์‚ฌ์šฉ ๋ฐฉ๋ฒ•์„ ์ข€ ๋” HOF์Šค๋Ÿฝ๊ฒŒ ํ’€์–ด๋‚ด๋Š” ๋ฐฉ๋ฒ•

withHOC.js

import component from '๊ฒฝ๋กœ';

export default function withHOC(component) {
  return {
    name,
     // ๊ณตํ†ต์ ์ธ ๋กœ์ง
    created() {    
    },
    render(createElement) {
      return createElement(component);
    }
  }
}

๋‹จ์ 

HOC๋ฅผ ๋งŽ์ด ์“ฐ๋ฉด ์“ธ์ˆ˜๋ก ๊ทธ๋งŒํผ ์ปดํฌ๋„ŒํŠธ ๊นŠ์ด๊ฐ€ ๊นŠ์–ด์ง์— ๋”ฐ๋ผ ์ปดํฌ๋„ŒํŠธ ๊ฐ„ ํ†ต์‹ ์— ๋ถˆํŽธํ•จ์ด ๋ฐœ์ƒ

profile
Front-End ๐Ÿ˜ฒ

0๊ฐœ์˜ ๋Œ“๊ธ€