Svelte

[Svelte]생명주기(Lifecycle) - afterUpdate 함수

DevStory 2022. 8. 9.

afterUpdate 함수

Svelte의 생명주기 함수인 afterUpdate() 함수는 컴포넌트의 변경된 값이 DOM에 적용 후 호출됩니다. 즉, 변경된 값이 DOM에 영향이 있으면 호출되고 영향이 없으면 호출되지 않습니다.

 

다음 예제는 간단한 소스 코드입니다. num++ 버튼을 클릭하면 변수 numValue의 값을 1씩 증가시킵니다.

<script>
  import { afterUpdate } from 'svelte';

  let numValue = 0;
  
  afterUpdate(() => {
    console.log('App Component afterUpdate Call');
  });

  const handleClick = () => {
    numValue++;
  }
</script>

<div>
  <button on:click={handleClick}>
    num++
  </button>
  <p>App: {numValue}</p>
</div>

[실행 결과]

컴포넌트가 DOM에 추가된 후 afterUpdate() 함수가 최초 한 번 실행됩니다.

 

num++ 버튼 클릭 후 변수 numValue의 값이 1씩 증가할 때마다 변경된 numValue의 값을 웹 브라우저에서 확인할 수 있으며, 콘솔 창에서 afterUpdate() 함수에 작성된 문구가 출력됩니다.


값을 화면에 표시하지 않을 경우

다음 소스 코드처럼 변수 numValue의 값을 HTML 영역에 표시하지 않는다면 afterUpdate() 함수는 동작하지 않습니다.

<script>
  import { afterUpdate } from 'svelte';

  let numValue = 0;
  
  afterUpdate(() => {
    console.log('App Component afterUpdate Call');
  });

  const handleClick = () => {
    numValue++;
  }
</script>

<div>
  <button on:click={handleClick}>
    num++
  </button>
</div>

[실행 결과]

컴포넌트가 DOM에 추가된 후 afterUpdate() 함수가 최초 한 번 실행되고 변수 numValue의 값을 화면에 표시하지 않으므로 numValue의 값이 변경되더라도 afterUpdate() 함수가 호출되지 않습니다.


afterUpdate 함수가 호출되는 시점

컴포넌트의 변경된 값이 DOM에 적용된 후 afterUpdate() 함수가 호출되는지 자세하게 알아봅시다. 다음 소스 코드는 afterUpdate() 함수에서 debugger 키워드를 사용합니다.

 

따라서, afterUpdate() 함수의 debugger 키워드가 실행되면 웹 어플리케이션이 중지됩니다.

<script>
  import { afterUpdate } from 'svelte';

  let numValue = 0;
  
  afterUpdate(() => {
    console.log('App Component afterUpdate Call');
    debugger;
  });

  const handleClick = () => {
    numValue++;
  }
</script>

<div>
  <button on:click={handleClick}>
    num++
  </button>
  <p>App: {numValue}</p>
</div>

[실행 결과]

변경된 numValue의 값이 DOM에 적용 후 afterUpdate() 함수의 debugger 키워드가 실행되었습니다. 따라서, 컴포넌트에서 변경된 값이 DOM에 적용된 후 afterUpdate() 함수가 호출되는 것을 알 수 있습니다.


정리

  • Svelte의 생명주기 함수인 afterUpdate() 함수는 컴포넌트에서 변경된 값이 DOM에 적용된 후 호출되는 함수입니다.
  • 컴포넌트에서 변경된 값이 DOM에 영향이 없는 경우 afterUpdate() 함수는 실행되지 않습니다.
  • 컴포넌트가 DOM에 추가된 후 최초 한 번 실행됩니다.
반응형

댓글