어쩌다 알게 된 ƪ(•̃͡•̃͡ ƪ

컴포넌트와 함수 선언 순서, 실행 순서_코드리뷰 본문

개발/🟦 React

컴포넌트와 함수 선언 순서, 실행 순서_코드리뷰

비니_ 2025. 11. 20. 10:00
728x90

 

 

저번에 함수형 컴포넌트와 선언형 컴포넌트에서 선언 순서에 따라 실행여부가 달라지는 걸 보고

내 코드를 봤는데 의문이 들었따🤔❓

 

현재 코드

function CommonCalendar({
        date,
        events,
        localizer,
        toolbar = false,
        onNavigate,
        eventPropGetter
    }){
        const month = getMonth(date) + 1;
        const year = getYear(date);

        return(
            <>
                <div className="tit_box">
                    <Button
                        className='border-light btn_prev'
                        color='dark'
                        isOutline
                        icon='ChevronLeft'
                        aria-label='Prev'
                        onClick={btnPrevMonth}
                    />
                    <div className="month_date">
                        {formatByLang(date, "LLLL yyyy", language)}
                    </div>
                    <Button
                        className='border-light btn_next'
                        color='dark'
                        isOutline
                        icon='ChevronRight'
                        aria-label='Next'
                        onClick={btnNextMonth}
                    />
                </div>
                <div className="calendar_box">
                    <Calendar
                        localizer={localizer}
                        events={events}
                        date={date}
                        views={["month"]}
                        toolbar={toolbar}
                        eventPropGetter={eventPropGetter}
                        startAccessor="start"
                        endAccessor="end"
                        onNavigate={onNavigate}
                        components={{
                            event: CustomEvent,
                            header: CustomHeader,
                            dateCellWrapper: (props) => <CustomDayCell {...props} month={month} year={year} />,
                            dateHeader: (props) => <CustomDayCellHeaderContent {...props} month={month} year={year} />,
                        }}
                        selectable
                        resizable
                    />
                </div>
            </>
        )
    };

    // custom navigate
    const [currentDate, setCurrentDate] = useState(new Date());
    const handleNavigate = (date, view, action) => {
        setCurrentDate(date);
    }

    const btnPrevMonth = () => {
        setCurrentDate(prev => addMonths(prev, -1));
    }

    const btnNextMonth = () => {
        setCurrentDate(prev => addMonths(prev, 1));
    }

 

 

이것만 봤을 때는 실행이 안되어야 하는 코드인데 알고보니

저 CommonCalendar 컴포넌트 호을 밑에서 해주기 때문에 가능한 것

=> “선언 순서가 아니라 실행 순서” 때문에 작동 가능

return(
	<CommonCalendar
        localizer={localizer}
        date={currentDate}
        events={events}
        onNavigate={handleNavigate}
    />
)

 

👌

CommonCalendar 컴포넌트는 함수 선언이기 때문에 호이스팅으로 위로 끌어올려지지만,
실제로 함수가 실행되는 시점은 return ( <CommonCalendar .../> )이 호출될 때이며,

그 시점은 btnPrevMonth 등이 const로 모두 초기화된 후이기 때문!

 

 

❌ 안되는 경우 예시

function CommonCalendar() {
    btnPrevMonth();  // ❌ 실행 시점이 아니라 선언 시점에 접근하기 때문에 불가
}

const btnPrevMonth = () => {}

 

 

🔖🔖🔖정리

** function은 메뉴판에 등록된 요리 이름

** const 함수는 요리사가 실제로 재료를 준비하는 단계

 

  1. 메뉴판에 요리 이름(CommonCalendar)이 먼저 등록됨
  2. 요리사(btnPrevMonth 등)가 나중에 재료를 준비함
  3. 마지막에 손님(React 렌더링)이 요리를 주문함 → 그때는 이미 재료 준비 완료

 

 

 

 

화살표 함수 컴포넌트, 함수 선언문 컴포넌트 형태와 사용 차이

✅ ① 화살표 함수 컴포넌트 ( React 컴포넌트 ⭕, 커스텀 훅 ⭕, 일반 유틸 함수 ⭕)const Test = () => { return Test;};장점일관된 스코프(lexical this) → class 기반 this 문제 없음재정의 방지 가능 (const라 재

dazzle-bini.tistory.com

 

 

 

728x90
Comments