투두리스트에 날짜를 불러오는 컴포넌트이다.
변경 전 코드는 함수를 만들어 if 매칭을 통해 날짜를 불러온다.
이 코드에서 나의 문제점은
1. 많은 조건을 매칭할 때는 if 보다는 switch/case문을 사용하자!
- if는 하나하나 앞에 있는 조건을 다 검사하고 타고타고 내려온다
- 하지만 switch case 문은 점프가 가능하다! 조건을 메모리에 들고 있기 때믄에 특정 조건을 만났을 때 위에서 부터 아래로 내려가서 하나하나 검사하는 것이 아닌 그 조건 케이스로 점프가 가능해진다.
- 하지만 보통 1:1 매칭이 가능한 것은 객체 혹은 배열로 사용하는 것이 더 좋다!
2. state의 필요성
- 함수 안에 있는 상수들은 변하지 않는 값들이다. 이것은 state가 변경될 때 함수가 다시 실행이 되어 불필요한 함수 생성을 하게된다. 이런 것은 컴포넌트 밖에다 풀어주는 것이 베스트이다.
- 그리고 보통 시간 데이터는 다른 연산에 비해 무거운 편! => 이때 useMemo를 사용하여 성능 최적화를 해보자
- .toLocaleDateString("ko-KR") 이 함수는 시간을 그냥 한국 형식으로 뽑아주는 것. 위치가 변경되면 이상하게 동작을 한다.new Date는 내가 위치해 있는 로컬 타임을 따라가기 때문에 그대로 사용하면 된다!
import React, { useState, useEffect } from "react";
import "./style.css";
interface IDate {
  day: string;
  month:
    | "JANUARY"
    | "FABRUARY"
    | "MARCH"
    | "APRIL"
    | "MAY"
    | "JUNE"
    | "JULY"
    | "AUGUST"
    | "SEPTEMBER"
    | "OCTOBER"
    | "NOVEMBER"
    | "DECEMBER";
  weekDay: "MON" | "TUE" | "WED" | "THU" | "FRI" | "SAT" | "SUN";
}
function TodayDate() {
  const [currentDate, setCurrentDate] = useState<IDate>({
    day: "1",
    month: "JANUARY",
    weekDay: "SUN",
  });
  const changeMonth = (month: string) => {
    if (month === "1") return "JANUARY";
    if (month === "2") return "FABRUARY";
    if (month === "3") return "MARCH";
    if (month === "4") return "APRIL";
    if (month === "5") return "MAY";
    if (month === "6") return "JUNE";
    if (month === "7") return "JULY";
    if (month === "8") return "AUGUST";
    if (month === "9") return "SEPTEMBER";
    if (month === "10") return "OCTOBER";
    if (month === "11") return "NOVEMBER";
    if (month === "12") return "DECEMBER";
  };
  const changeWeekDay = (weekDay: number) => {
    if (weekDay === 0) return "SUN";
    if (weekDay === 1) return "MON";
    if (weekDay === 2) return "TUE";
    if (weekDay === 3) return "WED";
    if (weekDay === 4) return "THU";
    if (weekDay === 5) return "FRI";
    if (weekDay === 6) return "SAT";
  };
  useEffect(() => {
    const koreanDate = new Date().toLocaleDateString("ko-KR");
    const date = koreanDate.split(".");
    setCurrentDate({
      day: date[2].trim(),
      month: changeMonth(date[1].trim()) ?? "JANUARY",
      weekDay: changeWeekDay(new Date().getDay()) ?? "SUN",
    });
  }, []);
  return (
    <div className="date">
      <span className="day">{currentDate.day}</span>
      <div className="right-side">
        <span className="weekDay">{currentDate.weekDay}</span>
        <span className="month">{currentDate.month}</span>
      </div>
    </div>
  );
}
export default TodayDate;
변경 후
- if문을 삭제!
- 컴포넌트 밖에다 상수를 만들고
- 불필요한 state는 삭제!
- useMemo로 최적화
import { useMemo } from "react";
import "./style.css";
const MONTHS = [
  "JANUARY",
  "FABRUARY",
  "MARCH",
  "APRIL",
  "MAY",
  "JUNE",
  "JULY",
  "AUGUST",
  "SEPTEMBER",
  "OCTOBER",
  "NOVEMBER",
  "DECEMBER",
];
const WEEKDAYS = ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"];
function TodayDate() {
  const { month, weekDay, day } = useMemo(() => {
    const now = new Date();
    const month = now.getMonth();
    const weekDay = now.getDay();
    const day = now.getDate();
    return { month: MONTHS[month], weekDay: WEEKDAYS[weekDay], day };
  }, []);
  return (
    <div className="date">
      <span className="day">{day}</span>
      <div className="right-side">
        <span className="weekDay">{weekDay}</span>
        <span className="month">{month}</span>
      </div>
    </div>
  );
}
export default TodayDate;훠월씬 깔끔해진 것을 볼 수 있다.
'React' 카테고리의 다른 글
| state 지연 초기화 (0) | 2023.08.01 | 
|---|---|
| 렌더링 로직과 데이터 받아오는 로직 분리 (0) | 2023.08.01 | 
| lazy&suspense (0) | 2023.07.17 | 
| [React]SPA와 라우팅 (0) | 2022.11.23 | 
| [ 리액트 ] 컴포넌트 패턴 유의사항!! (0) | 2022.04.05 |