React Hook - useMemo

BANG·2025년 8월 29일
import { useRef, useEffect, useState, useMemo } from 'react';

// 성능이 비싼 연산은 useMemo로 캐싱하기
const hardCalcuate = (num) => {
  for(let i = 0; i < 999999999; i++){}
  console.log("hard cal");
  return num + 10000;
};

const easyCalcuate = (num) => {
  console.log("easy cal");
    return num + 1;
};

const App = () => {
  // React 함수형 컴포넌트는 state가 바뀔 때마다 전체 함수가 다시 실행
  const [hardNum, setHardNum] = useState(1);
  const [easyNum, setEasyNum] = useState(1);

  // const hardSum = hardCalcuate(hardNum);
  const hardSum = useMemo(() => {
    return hardCalcuate(hardNum);
  }, [hardNum]);
  const easySum = easyCalcuate(easyNum);

  return (
    <div>
      <h3>hard 계산기</h3>
      <input type='number' value={hardNum}
      onChange={(event) => setHardNum(parseInt(event.target.value))}>
      </input>
      <span> + 10000 = {hardSum}</span>

      <h3>easy 계산기</h3>
      <input type='number' value={easyNum}
      onChange={(event) => setEasyNum(parseInt(event.target.value))}>
      </input>
      <span> + 1 = {easySum}</span>
    </div>  
  )
};

export default App;
import { useRef, useEffect, useState, useMemo } from 'react';


const App = () => {
  const [number, setNumber] = useState(0);
  const [isKorea, setIsKorea] = useState(true);

  // 원시 타입이 아닌 객체타입, 인스턴스를 새로 생성해 할당하므로 주소값이 달라짐
  //const location = {country: isKorea ? '한국' : '외국'};

  const location = useMemo(() => {
    return {country: isKorea ? '한국' : '외국'};
  }, [isKorea]);

  useEffect(() => {
    console.log("useEffect");
  }, [location]);
  
  return (
    <div>
      <h2>하루에 몇끼 먹어요?</h2>
      <input type='number' value={number}
      onChange={(event) => setNumber(event.target.value)}></input>
      <hr />
      <h2>어느 나라에서 왔어요?</h2>
      <p>나라: {location.country}</p>
      <button onClick={(event) => setIsKorea(!isKorea)}>비행기 타자</button>
    </div>  
  )
};

export default App;
profile
Record Everything!!

0개의 댓글