High Order Function (HOF)

Tony·2021년 9월 1일
0

react

목록 보기
23/82

이번에 이벤트 리스너의 콜백함수에로 값을 전달해야 될때 HOF으로도 가능하다는 것을 알았다

코드 1-1.

// 기존 사용 방식 : 이벤트 콜백함수에 인자가 필요하면 익명함수 형태로 전달
const onClickButton = (textList: string[], index:number, boxType: 'whatYouCanLearn' | 'expectedStudents' | 'requiredKnowledge') => {
  const textArray = [...textList];
  textArray.splice(index, 1);
  switch (boxType) {
        case 'whatYouCanLearn':
          dispatch({
            type: DELETE_ITEM_WHATYOUCANLEARN,
            data: textArray,
          });
          break;
        case 'expectedStudents':
          dispatch({
            type: DELETE_ITEM_EXPECTEDSTUDENTS,
            data: textArray,
          });
          break;
        case 'requiredKnowledge':
          dispatch({
            type: DELETE_ITEM_REQUIREDKNOWLEDGE,
            data: textArray,
          });
          break;
        default:
          console.error('boxType is wrong');
      }
}

<TextListBox key={index} onClick={() => onClickButton(data?.textlist, index)} />

코드 1-2.

// 새롭게 적용하는 방식 : 함수를 리턴하는 함수를 만들어서 전달
const onClickButton = (textList: string[], index:number, boxType: 'whatYouCanLearn' | 'expectedStudents' | 'requiredKnowledge') = () => {
  const textArray = [...textList];
  textArray.splice(index, 1);
  switch (boxType) {
        case 'whatYouCanLearn':
          dispatch({
            type: DELETE_ITEM_WHATYOUCANLEARN,
            data: textArray,
          });
          break;
        case 'expectedStudents':
          dispatch({
            type: DELETE_ITEM_EXPECTEDSTUDENTS,
            data: textArray,
          });
          break;
        case 'requiredKnowledge':
          dispatch({
            type: DELETE_ITEM_REQUIREDKNOWLEDGE,
            data: textArray,
          });
          break;
        default:
          console.error('boxType is wrong');
      }
}

<TextListBox key={index} onClick={onClickButton(data?.textlist, index)}

그 전엔 anonymous 함수를 그 자리에서 만들어서 값을 전달했었는데 더 섹시한 방법이 있는 걸 알게 되니 앞으로 이렇게 사용해야겠다는 생각이 든다

그 전에 HOF가 무엇인지 명확히 알고갈 필요가 있다

High Order Function

  • 하나 이상의 함수를 인자로 받는다.
  • 함수를 결과로 반환한다.

Use Case

array method

  • Array.prototype.filter(), map(), reducer()
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);

console.log(result);
  • filter()
  • 필터링 하는 조건을 함수를 통해 제어하는 것

ramda

  • 읽어봐도 잘 모르겠다.

내가 작성한 코드는 HOF 인가?

useCallback

  • 함수 memoization(메모이제이션)하기 위해 사용되는 hook 함수
  • 컴포넌트 안에 함수가 선언이 되어 있다면 해당 컴포넌트가 렌더링 될 때 마다 새로운 함수가 생성 됨
    • course_info가 페이지 그 자체이므로 렌더링이 다시 될일은 없어서 useCallback을 사용해도 아무런 효과가 없을 것 같다.

참고 문헌

관련 커밋

profile
움직이는 만큼 행복해진다

0개의 댓글