[BFE.dev] lazy initial state

치만·2026년 1월 23일

BFE.dev react

목록 보기
18/28
post-thumbnail

lazy initial state

👉 Lazy initial state 개념 설명

// This is a React Quiz from BFE.dev

import * as React from 'react'
import { useState, useEffect } from 'react'
import { createRoot } from 'react-dom/client'

function App() {
  const [state1, setState1] = useState(1);

  const [state2] = useState(() => {
    console.log(2);
    return 2;
  });

  console.log(state1);

  useEffect(() => {
    setState1(3);
  }, []);

  return null;
}

const root = createRoot(document.getElementById("root"));
root.render(<App />);

출력 결과

2
1
3

풀이 과정

1. 초기 렌더링

  • 2 출력: useState(() => { ... })의 형태는 Lazy Initial state로 비용이 큰 연산의 경우일 때 사용합니다. 컴포넌트가 처음 마운트될 때만 실행하여 초기값을 결정합니다.

  • 1 출력: state11로 초기화되어 출력됩니다.


2. 상태 업데이트 후 재렌더링

  • 3 출력: setState에 의해 state13로 출력됩니다.
profile
🌱개발 기록장

0개의 댓글