<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Yeoul on Medium]]></title>
        <description><![CDATA[Stories by Yeoul on Medium]]></description>
        <link>https://medium.com/@sckimynwa?source=rss-9ce465f93d9e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*YxfvorvpgqDEKl06cBUfFA.png</url>
            <title>Stories by Yeoul on Medium</title>
            <link>https://medium.com/@sckimynwa?source=rss-9ce465f93d9e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 19:42:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sckimynwa/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[콴다 팀의 Typed Format Renderer 서비스 개발기]]></title>
            <link>https://blog.mathpresso.com/%EC%BD%B4%EB%8B%A4-%ED%8C%80%EC%9D%98-typed-format-renderer-%EC%84%9C%EB%B9%84%EC%8A%A4-%EA%B0%9C%EB%B0%9C%EA%B8%B0-d50c5da96e7c?source=rss-9ce465f93d9e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d50c5da96e7c</guid>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[febe]]></category>
            <category><![CDATA[message-queue]]></category>
            <category><![CDATA[frontend]]></category>
            <dc:creator><![CDATA[Yeoul]]></dc:creator>
            <pubDate>Tue, 10 Oct 2023 06:01:37 GMT</pubDate>
            <atom:updated>2023-10-10T06:01:39.248Z</atom:updated>
            <content:encoded><![CDATA[<h4>image / pdf 를 만드는 과정</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aoFBUfaAqICxQgJy45verQ.png" /></figure><p>콴다에서는 수억 개의 질문(Question) &amp; 답변(Answer) 데이터 이외에도 학생들에게 양질의 콘텐츠를 제공하기 위한 수십만 개의 문제 / 해설 데이터를 보유하고 있습니다. 이 데이터는 콴다 내의 여러 서비스들을 사용하는 사용자들에게 양질의 문제 / 해설을 제공하는 데 사용됩니다.</p><p>PDF, Image, 텍스트 등 어떤 형태로든 데이터를 수급받으면 이를 구조화된 객체(<em>타이핑된 형태라는 의미로 이를 TypedFormat이라고 부르고 있습니다</em>)의 형태로 Stringify하여 저장하고 있기 때문에, 실제로 사용자에게 이를 제공하기 위해서는 이를 다시 객체화 하여 사용자의 유즈케이스에 따라 사용자의 기기에 가장 적합한 형태 (image, pdf)로 변환하는 과정이 필요합니다. 콴다에서는 이 변환 과정을 Typed Format Renderer(이하 Renderer)라는 서비스를 만들어 처리하고 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*e3tsoM6cL4PVLMFIJgKTgQ.png" /><figcaption>간략하게 도식화된 콘텐츠 생산과 image / pdf 생성 도식</figcaption></figure><p>이번 글에서는 이 Renderer 서비스가 적게는 수천 개에서, 많게는 수만 개의 image / pdf 생성 요청을 감당하기 위해서 어떤 기술적인 고민을 거쳐왔는지를 살펴보고자 합니다.</p><h3>Background</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AKnRLouM3DIFIp8Tl8i9NA.png" /><figcaption>Renderer 가 렌더한 일로학원 과제 pdf의 일부</figcaption></figure><p>앞선 Overview에서 간략하게 설명했듯, Renderer는 문제나 해설에 대한 데이터와 메타데이터를 담고 있는 Stringify된 객체(TypedFormat) 스트링, 혹은 이들의 배열을 받아서 Image나 PDF를 렌더하는 Stateless Server 입니다.</p><p>수급된 콘텐츠의 품질을 유지하기 위한 검수 과정까지 마치게 되면, 해당 데이터들을 콴다의 모든 콘텐츠가 저장되는 “ContentHub” 라는 서버에 Publish 하게 됩니다. 이때 이 ContentHub는 Publish된 데이터들을 가지고 Renderer를 호출해서 수천, 수만 건의 Image와 PDF를 생성합니다.</p><p>서비스의 특성상, 지속적으로 특정 규모의 트래픽이 유입되는 것이 아니라 시험 기간과 같은 특정한 이벤트가 있을 때 비동기적으로 대량의 트래픽이 유입되기 때문에 평상시에는 최소 개수의 Instance 만을 유지하다가 갑자기 트래픽이 유입 되었을 때 이 요청들을 Drop하지 않고 안정적으로 서비스할 수 있는 구조를 고민하는 것이 중요했습니다.</p><p>또한 Renderer가 동작하는 방식으로 인해 하나의 요청을 처리하는데 걸리는 시간이 적게는 2~4초, 문제집 형태의 PDF의 경우 40~50초 가까이 걸리기도 하기 때문에, “<em>처리하는데 오랜 시간이 걸리는 수천~수만 개의 요청을 안정적으로 서비스 하기 위한</em>” 고민해야 했습니다.</p><h3>How Renderer Works (Before)</h3><p>기존의 Renderer는 NodeJS 런타임에서 Headless Browser(Puppeteer)를 사용해 콘텐츠를 하나의 Browsing Context에 렌더하고 전처리, 후처리 과정을 거쳐 Image / PDF를 생성한 뒤 이를 Stream의 형태로 반환합니다. 이를 조금 더 자세하게 살펴보면 다음과 같습니다</p><ol><li>ContentHub로부터 넘어온 요청에 대한 Validation을 수행한다.</li><li>Validated된 객체(TypedFormat)을 화면에 그리기 위해서 서버에 Browser Instance 하나를 요청한다. (아래 그림과 같이 Renderer는 빠른 응답 속도를 위해 N개의 Browser Instance를 미리 만들어 Pool을 사용해서 관리하고 있으며, 요청이 오면 이미 생성된 Browser Instance를 Pool에서 꺼내서 주고, 요청을 다 처리하고 다면 Instance를 다시 초기화한 후 반환합니다.)</li><li>Image의 경우 렌더된 영역만큼 Screenshot으로 찍은 뒤 Stream의 형태로 요청한 서버에 반환한다.</li><li>PDF의 경우 PDF에 포함될 모든 문제를 일단 화면에 한번 렌더한 후, 렌더된 각 영역의 크기를 계산해서 한 페이지에 얼마만큼의 문제가 들어갈 수 있는지를 구하고, 이를 바탕으로 여러 페이지에 걸친 문제집 형태의 템플릿 안에 문제들을 배치한다. 이후 Stream의 형태로 요청한 서버에 반환한다.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*8Q61FWaZzTeHoKNP3O9ruw.png" /><figcaption>How TF Renderer Works Inside (Using Pool)</figcaption></figure><p>위에서 살펴본 것처럼, Renderer는 기본적으로 여러 개의 Headless Browser Instance를 동작시켜 렌더하는 과정을 거치기 때문에 CPU Heavy한 작업이며, 아래 보이는 것과 같이 하나의 Instance안에 여러 개의 브라우저 프로세스가 동작하기 때문에 적지 않은 리소스를 사용하게 됩니다. 하지만, 이렇게 브라우저를 사용해서 Image / PDF를 생성하기 때문에 프론트엔드 엔지니어분들이 기술적으로 쉽게 Image / PDF의 레이아웃을 수정할 수 있다는 장점도 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*NFDp8s4ffeAMMVw1fYdn9Q.png" /><figcaption>k8s cluster 안에 떠있는 tf-renderer-worker의 process list. renderer와 gpu process가 10개씩 떠있다.</figcaption></figure><p>Renderer는 기존에 Cloud Run이라는 GCP Managed Service를 사용해서 서비스되고 있었습니다. 다른 여러 가지 방법들을 사용해서 배포할 수도 있지만, 처음 Renderer를 배포하는 당시에는 다음과 같은 사항들을 고려하여 Cloud Run을 사용하게 되었습니다.</p><ol><li>Cloud Run은 Managed Service이기 때문에 배포 설정이 비교적 간단합니다. Renderer 서버의 컨테이너 이미지만 빌드해서 제공하면 나머지는 Cloud Run 에서 다 관리해준다는 장점이 있습니다.</li><li>GCP Console에서 Renderer가 제대로 동작하고 있는지를 알아보기 위한 여러 지표 및 로그들을 기본적으로 제공합니다. 서버로그 뿐 아니라, CPU / Memory / Concurrency / Status등의 여러 유용한 지표들을 별다른 설정 없이 기본적으로 제공되는 콘솔에서 확인할 수 있습니다.</li><li>요청이 간헐적으로 들어오는 서비스인만큼, 사용량이 없을 때 0개의 Instance로 운영하는 “Scale To Zero” 전략을 사용할 수 있었습니다.</li><li>처음에는 비교적 렌더링 속도가 빠른 이미지와 매우 단순한 형태의 가벼운 PDF를 생성하기 위한 서비스로 시작하였으므로 빠르게 개발 / 배포하여 서비스에 올리는 것이 중요했고, 프론트엔드 엔지니어가 빠르게 설정하여 배포하기에 용이했습니다.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a8JJZPncJhJxM2JuQnkq9g.png" /><figcaption>CloudRun에서 제공하는 여러 지표들. 이외에도 CPU, Memory Utilization등 여러 유용한 지표들을 제공한다</figcaption></figure><h3>Problems</h3><p>하지만 이렇게 Render를 Cloud Run에서 서비스하는 기존의 방식에는 몇 가지 문제가 있었습니다.</p><ol><li><strong>Cloud Run의 Scale Up이 생각만큼 유연하게 잘 되지 않음:</strong><br>Cloud Run에서 기본적으로 Scaling 옵션을 지원하긴 하지만, 이것이 갑자기 다량의 트래픽이 몰려드는 상황에서는 의도한 대로 동작하지 않을 때가 많았습니다. <br>실제로 Production에서 Min Instance Count를 10으로, Max Instance Count를 150으로 잡아두었지만, 실제 다량의 트래픽(수천 개)이 몰리는 상황에서 40개 정도밖에 Scaling이 되지 않았고, Host Machine의 CPU / Memory 사양을 조절해 보거나, Concurrency를 조절해 보아도 원하는 만큼의 Scalability를 달성할 수 없었습니다.</li><li><strong>요청을 처리하는 시간이 너무 오래 걸려서 요청을 보낸 서버도 Connection을 길게 유지하고 있어야 함:<br></strong>특히 PDF를 생성하는 경우, 문제를 렌더하고 렌더된 크기에 맞게 문제를 재배치하고, 재배치된 문제들을 A4 Page 단위로 나누어 Template을 적용하는데 적지 않은 시간이 소요됩니다. 하나의 서버가 수천 개의 PDF 생성을 요청하는 경우 이 수천 개의 오래걸리는 커넥션들을 유지하고 있어야 하므로 안정적이지 않으며, 모종의 이유로 커넥션이 끊어진 경우 Retry의 책임이 요청하는 서버에 넘어가게 됩니다.</li></ol><h3>How TF Renderer Works (After)</h3><p>위에서 제시된 문제를 해결하기 위해서 다음과 같은 변화를 주었습니다.</p><ol><li>CloudRun에서 동작하던 Renderer를 Kubernetes Cluster 위에서 동작하도록 변경하였음.</li><li>Cloud Pub/Sub을 사용해서 요청을 보낸 서버(ContentHub)와 TF Renderer사이의 결합도를 낮추었음.</li></ol><p>이를 통해 변경된 전반적인 구조는 다음과 같습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L5jRnXolmlJ2SrY6zqEblw.png" /></figure><ol><li>기존의 Renderer를 tf-renderer-scheduler(이하 scheduler)와 tf-renderer-worker(이하 worker)의 2개로 분리합니다. scheduler는 요청을 받아서 Pub/Sub Topic에 Publish하는 역할을 하고, worker 는 Pub/Sub Topic을 Subscribe해서 요청을 처리하는 역할을 합니다.</li><li>ContentHub가 생성해야 하는 Image/ PDF에 대한 요청을 scheduler에게 전달합니다. scheduler는 이 요청에 대해 validation 작업을 수행한 후, 유효하다면 이 메시지를 Pub/Sub에 Publish한 후 ContentHub에 리턴합니다.</li><li>만약 scheduler 로 들어온 요청이 유효하지 않은 경우, (e.g callback Uri가 잘못되었다거나, 필수 옵션이 누락되었거나) scheduler는 Pub/Sub에 Publish하지 않고 바로 Error를 리턴합니다. 이렇게 해서 worker가 처리할 수 있는 메시지만 Pub/Sub에 쌓일 수 있도록 합니다.</li><li>worker는 Pub/Sub을 Streaming Pull 방식으로 구독하고 있다가 메시지가 넘어오면 이 메시지 안의 데이터를 사용해 Image / PDF를 렌더하고, 이 결과물을 stream으로 받아서 메시지 안에 들어있는 ContentHub의 Object Uri를 사용해서 ContentHub의 Storage에 streaming upload를 수행 합니다.</li><li>Upload가 완료되면, 메시지 안에 들어있는 ContentHub의 Callback Uri를 사용해서 요청 처리가 완료되었음을 알려줍니다.</li></ol><h3>Implementation Detail</h3><p><strong>Scaling</strong>:<br>Renderer를 Cluster 안으로 옮긴 가장 큰 이유 중 하나는 Instance를 Kubernetes의 관리 아래 두어 조금 더 자유로운 설정들을 제공하기 위해서 입니다. 특히 Cloud Run에서 Kubernetes Cluster로 넘어오면서 worker instance가 뜨는 Pod의 Scaling Metric을 num_undelivered_messages 즉 Message Queue의 잔여 메시지 개수 기준으로 설정할 수 있게 되었는데, 이는 Cloud Run에 비해 조금 더 명시적이고 안정적인 Scaling 처리를 제공합니다. (Cloud Run의 경우 60% 정도의 CPU Target이나 concurrency option을 통해 조절해야 하며, 이외의 옵션은 당시 시점에서는 제공하지 않아서 Scaling Metric을 원하는대로 설정하기 어려웠습니다.)</p><p>예를 들어 아래와 같이 Pod의 autoscale 조건을 targetAverageValue: 5 로 설정해 두었다면, Message Queue에 처리되지 않은 메시지가 100개인 경우 20개까지 Scaling이 됩니다.</p><pre>...<br>resources:<br>    requests:<br>      cpu: 4000m<br>      memory: 4Gi<br>    limits:<br>      cpu: 4500m<br>      memory: 4Gi<br>            <br>    scaling:<br>      replicas: 1<br>      autoScaling:<br>        enabled: true<br>        minReplicas: 1<br>        maxReplicas: 50<br>        cpuTarget: 90<br>        custom:<br>          enabled: true<br>          metrics:<br>            - type: External<br>              metricName: pubsub.googleapis.com|subscription|num_undelivered_messages<br>              targetType: AverageValue<br>              targetAverageValue: 5<br>              matchLabels:<br>...</pre><p>물론 이렇게 설정한 경우에도 여러개의 인스턴스를 동시에 띄우기 위해서는 약간의 Starting Delay가 필요하지만, Cloud Run과는 다르게 결국 원하는 개수만큼 인스턴스 Scaling이 잘 되며, tf-renderer-worker가 가져갈 수 있는 만큼만 Message Queue로부터 가져가는 구조이기 때문에 요청이 너무 많아서 worker가 처리 불능이 되는 상태를 방지할 수 있습니다.</p><p>한 가지 주의할 점은, 서비스 특성상 평소에는 최소한의 Pod 개수만을 유지하다가 트래픽이 몰리는 특정 시점에 수십 개의 Pod가 떠야 하는 구조이므로, 이때 할당되는 리소스 사용량으로 인해, 콴다 서비스 내의 다른 애플리케이션이 영향을 받지 않아야 합니다. 따라서 DevOps Team과 논의하여 같은 클러스터 내에 별도의 Worker Node Pool을 할당해서 다른 애플리케이션들에 영향이 가지 않도록 설정했습니다.</p><p><strong>Streaming Pull</strong>:<br>Pub/Sub의 Subscriber가 메시지를 가져오는 2가지 방식 (pull, streaming pull) 중, worker는 Streaming Pull 방식으로 메시지를 가져오도록 구현했습니다. 이때 worker가 한 번에 streaming할 수 있는 최대의 메시지 개수를 의미하는 Max Messages와 관련된 몇 가지 옵션을 worker쪽에서 설정할 수 있는데, 이때 max message count를 하나의 worker에서 띄우는 최대 instance 개수와 동일한 수준으로 맞춰두면, 실제로 message queue에는 수천 개의 message가 쌓이더라도 kubernetes가 worker pod를 스케줄링하는 동안 하나의 Worker에서는 처리할 수 있는 만큼만 처리하게 되므로, 요청이 몰려서 worker가 작업 불능 상태가 되고 Pod가 kill 되는 현상을 막을 수 있었습니다.</p><pre>const subscription = pubSubClient.subscription(subscriptionName, {<br>  flowControl: {<br>    maxMessages: NUM_INSTANCES,<br>    allowExcessMessages: false,<br>  },<br>});</pre><p><strong>Dead Lettering:</strong><br>Message Queue에 Scheduler가 감지하지 못한 잘못된 메시지가 Publish된 경우, 그것이 어떤 이유인지를 늘 정확하게 감지하기는 어렵기 때문에 exponential backoff delay를 적용해 최대 5번 정도 retry한 후, 그래도 실패한다면, 이 메시지는 DeadLetter Topic으로 보내도록 설정해 두었습니다. 이때, 명시적으로 로그를 남기고 DeadLetter를 수동으로 처리하게 함으로써, 문제가 될 만한 상황을 최대한 방지하도록 합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*SSpqgEhtuitSbQe3zsan0Q.png" /><figcaption>GCP의 Pub/Sub Console 화면. 요청을 처리하기 위해 사용하는 job-request topic과, 처리되지 못한 메시지들을 처리하는 job-request-dl(dead-letter) topic을 확인할 수 있습니다.</figcaption></figure><h3>Result</h3><p>이렇게 구조를 변경한 후 1000개의 PDF 생성 요청을 scheduler로 보낸 결과입니다.</p><ul><li>PDF 1000개가 모두 잘 생성되어 ContentHub에서 관리하는 GCS(Google Cloud Storage) Bucket에 업로드되었습니다.</li><li>Message Queue에 Message가 잘 publish 되었고, Message Queue를 Subscribe하는 worker에 의해 Message가 잘 소비되어 잔여 메시지들(unacked messages)의 수가 잘 줄어드는 것을 확인할 수 있습니다.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*64HbkWwKnI2V6tRVyIb2iw.png" /></figure><ul><li>Message Queue의 잔여 메시지 수에 기반한 Scaling Metric에 의해 최대 개수(50개)까지 Scale up이 잘 되는 것을 확인할 수 있습니다.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DpG-v4DCs38sOoUPiki87w.png" /><figcaption>filtered: 50 즉, tf-renderer-worker 라는 이름의 pod가 현재 최대치인 50까지 Scale up 되었다는 의미이다</figcaption></figure><h3>Monitoring &amp; Tuning</h3><p>이제 Renderer가 의도한 대로 동작하게 되었으므로, 모니터링을 통해 최적의 리소스 할당을 해야 할 것입니다.</p><p>주요하게 살펴보았던 지표는 CPU Efficienty와 Memory Efficiency였고, PDF 1000개를 생성하면서 나타나는 정량적인 지표들을 통해 부족하다면 더 할당하고, 여유롭다면 줄이는 식으로 모니터링을 수행했습니다. Cluster 안에 배포했기 때문에, 기존에 콴다 팀이 Grafana를 사용해서 모니터링하던 방식을 그대로 사용할 수 있었습니다.</p><p><strong>CPU Target: </strong><br>2000m로 요청한 Pod의 리소스(주황색 점선)가 요청을 최대로 처리하고 있을 때 리소스 quota를 넘어가서 CPU Throttling이 발생하고 있었습니다. CPU Throttling이 일어나면 worker가 PDF 를 생성하는 과정 자체가 느려지기 때문에, CPU 리소스를 조금 더 넉넉하게 받는 것이 필요하겠다는 판단을 하고 조금 더 넉넉하게 CPU Target Resource를 요청했습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MkZTd8xDhcIbOVAFvOnSpw.png" /></figure><p><strong>Memory Target:</strong><br>부족하면 Throttling을 통해 처리 속도를 늦추는 방식을 사용할 수 있는 CPU와는 다르게, Memory의 경우 K8S 에 요청한 것보다 Application에서 사용하는 메모리의 양이 더 많으면 바로 OOM(Out Of Memory)에러가 나면서 Pod가 죽게 됩니다. 개발 환경에서 부하 테스트를 하다가 OOM 관련 에러가 발생하면서 Pod가 계속해서 재시작하는 현상을 파악한 후, worker 하나에 할당되는 메모리를 기존의 2Gi 보다 넉넉하게 요청했고, 그 결과 CPU / Memory 모두 80% 대의 Utilization을 보이면서 요청을 빠르게 처리할 수 있게 되었습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vEjX7JiWbYZfEGPpHab9Ow.png" /></figure><h3>Conclusion</h3><p>지금까지 콴다 팀에서 대량의 Image / PDF 생성 요청을 안정적으로 처리하기 위해서 고려했던 여러 가지 사항들에 대해 살펴보았습니다. 문제를 정의하고, 해결해 나가는 과정에서 Renderer라는 하나의 서비스를 제대로 동작하게 하기 위해서 이해해야 할 것이 상당히 많았고, 문제를 해결해 나가는 과정 자체가 재미있었던 것 같습니다.</p><p>어쩌다 보니 흔히들 이야기되는 “프론트엔드”에 관련한 내용이 거의 없는 채로 프론트엔드 섹션에 올라갈 글을 쓰게 된 것 같습니다. 하지만 콴다 프론트엔드 챕터에서는 전반적으로 문제를 정의하고 이것을 해결하기 위한 넓은 시야를 갖는 것을 중요하게 생각하고 있고, 이런 시야를 제공할 수 있는 좋은 문제를 발견한다면 이것을 직접 여러 과정을 거쳐 해결하는 것을 권장하고 있습니다.</p><p>유저로부터 가장 가까운 지점에서 더 나은 경험을 주기 위해 문제를 정의하고 해결하는 것을 프론트엔드 엔지니어라고 정의한다면, Renderer를 개선하는 이 전반적인 과정 뿐 아니라, 유저의 목소리를 듣는 것도, 더 나은 경험을 제공하기 위해 DevOps Team께 질문하면서 인프라를 개선하는 것도, 모두 프론트엔드 엔지니어가 할 수 있는 일일 것입니다.</p><p>🌏글로벌 Top 교육 앱 QANDA(콴다)를 함께 만들어 갈 Frontend 개발자들을 기다리고 있습니다! ➡️ <a href="https://team.mathpresso.com/">공고 확인하기</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d50c5da96e7c" width="1" height="1" alt=""><hr><p><a href="https://blog.mathpresso.com/%EC%BD%B4%EB%8B%A4-%ED%8C%80%EC%9D%98-typed-format-renderer-%EC%84%9C%EB%B9%84%EC%8A%A4-%EA%B0%9C%EB%B0%9C%EA%B8%B0-d50c5da96e7c">콴다 팀의 Typed Format Renderer 서비스 개발기</a> was originally published in <a href="https://blog.mathpresso.com/">Team QANDA</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Suspense Deep Dive (Code Implementation)]]></title>
            <link>https://blog.mathpresso.com/suspense-deep-dive-code-implementation-e766582a7366?source=rss-9ce465f93d9e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e766582a7366</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[suspense]]></category>
            <category><![CDATA[algebraic-effects]]></category>
            <category><![CDATA[web]]></category>
            <dc:creator><![CDATA[Yeoul]]></dc:creator>
            <pubDate>Sun, 26 Mar 2023 12:57:51 GMT</pubDate>
            <atom:updated>2023-03-26T12:57:51.424Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/612/0*xUiqWaVUb14hoWh2.jpg" /></figure><h3>Overview</h3><p>이전 포스팅 <a href="https://medium.com/mathpresso/conceptual-model-of-react-suspense-a7454273f82e">Conceptual Model of React Suspense</a>과, <a href="https://blog.mathpresso.com/algebraic-effects-of-react-suspense-157b49807ea0">Algebraic Effects of React Suspense</a>에서 React가 Suspense를 어떤 관점으로 바라보고 있는지, 그리고 어떤 개념적 모델을 바탕으로 구성되어 있는지를 살펴보았습니다. 이번 포스팅에서는 이러한 내용들을 바탕으로 Suspense가 실제로 React 소스 코드 레벨에서 어떻게 구현되어 있고, 구체적으로 어떤 과정을 거쳐 동작하게 되는지를 간략하게 살펴보도록 하겠습니다. (소스 코드는 글을 작성하는 시점의 최신 코드를 기반으로 하지만, React 프로젝트는 코드가 굉장히 자주 바뀌는 편이기 때문에 변경사항이 생길 수 있습니다.)</p><h3>Recap Example Code</h3><p>이전 포스팅에서 언급한 <a href="https://codesandbox.io/s/festive-elion-eb52b6">React 18 Suspense의 공식 예제</a>를 다시 보도록 하겠습니다. user와 post data를 fetching하는 동안 보여주어야 할 Loading Component를 각 컴포넌트에서 처리하는 것이 아니라 Suspense에서 선언적으로 처리하도록 하는 예제 입니다.</p><pre>// index.js<br>const resource = fetchProfileData();<br><br>function ProfilePage() {<br>  return (<br>    &lt;Suspense fallback={&lt;h1&gt;Loading profile...&lt;/h1&gt;}&gt;<br>      &lt;ProfileDetails /&gt;<br>      &lt;Suspense fallback={&lt;h1&gt;Loading posts...&lt;/h1&gt;}&gt;<br>        &lt;ProfileTimeline /&gt;<br>      &lt;/Suspense&gt;<br>    &lt;/Suspense&gt;<br>  );<br>}<br>function ProfileDetails() {<br>  // Try to read user info, although it might not have loaded yet<br>  const user = resource.user.read();<br>  return &lt;h1&gt;{user.name}&lt;/h1&gt;;<br>}<br>function ProfileTimeline() {<br>  // Try to read posts, although they might not have loaded yet<br>  const posts = resource.posts.read();<br>  return (<br>    &lt;ul&gt;<br>      {posts.map((post) =&gt; (<br>        &lt;li key={post.id}&gt;{post.text}&lt;/li&gt;<br>      ))}<br>    &lt;/ul&gt;<br>  );<br>}</pre><p>해당 컴포넌트에서 리소스를 불러오기 위해 사용하는 fetchProfileData라는 함수는 데이터 로딩시에 보여주어야 할 UI 로직을 Suspense로 넘기기 위해 다음과 같이 algebraic effect이 적용되어 있습니다. 즉, 데이터가 로딩 중일때는 <em>Suspense로 promise를 throw</em>하도록 구현되어 있다는 의미입니다.</p><pre>export function fetchProfileData() {<br>  let userPromise = fetchUser();<br>  let postsPromise = fetchPosts();<br>  return {<br>    user: wrapPromise(userPromise),<br>    posts: wrapPromise(postsPromise)<br>  };<br>}<br><br>// Suspense integrations like Relay implement<br>// a contract like this to integrate with React.<br>// Real implementations can be significantly more complex.<br>// Don&#39;t copy-paste this into your project!<br>function wrapPromise(promise) {<br>  let status = &quot;pending&quot;;<br>  let result;<br>  let suspender = promise.then(<br>    (r) =&gt; {<br>      status = &quot;success&quot;;<br>      result = r;<br>    },<br>    (e) =&gt; {<br>      status = &quot;error&quot;;<br>      result = e;<br>    }<br>  );<br>  return {<br>    read() {<br>      if (status === &quot;pending&quot;) {<br>        throw suspender;<br>      } else if (status === &quot;error&quot;) {<br>        throw result;<br>      } else if (status === &quot;success&quot;) {<br>        return result;<br>      }<br>    }<br>  };<br>}</pre><h3>Brief Pipeline</h3><p>Suspense의 로직을 크게 두 가지 부분으로 나누어 설명하려고 합니다. 첫 번째는 Scheduler에 의해 스케줄된 Task를 workLoop에서 처리할 때, Suspense와 Fallback Component, Child Component를 렌더링하는 부분이고, 두 번째는 Data Fetching 시에 throw한 Promise를 처리하는 부분입니다.</p><h3>Rendering</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/0*URbZMQSz1EUtbTM7.png" /></figure><h4>beginwork</h4><p>React Reconciler에서는 스케줄러에 의해 스케줄된 Task를 workLoop를 돌면서 렌더링합니다. 이때 매 루프마다 작업되는 단위가 performUnitOfWork로 감싸진 beginWork 인데, beginWork로 넘겨진 workInProgress의 tag가 “SuspenseComponent”인 경우, Suspense Component를 처리하기 위한 updateSuspenseComponent 함수를 호출합니다.</p><pre>/** @noinline */<br>function workLoopConcurrent() {<br>  // Perform work until Scheduler asks us to yield<br>  while (workInProgress !== null &amp;&amp; !shouldYield()) {<br>    // $FlowFixMe[incompatible-call] found when upgrading Flow<br>    performUnitOfWork(workInProgress);<br>  }<br>}<br>function performUnitOfWork(unitOfWork: Fiber): void {<br> ...<br>  let next;<br>  if (enableProfilerTimer &amp;&amp; (unitOfWork.mode &amp; ProfileMode) !== NoMode) {<br>    startProfilerTimer(unitOfWork);<br>    next = beginWork(current, unitOfWork, renderLanes);<br>    stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true);<br>  } else {<br>    next = beginWork(current, unitOfWork, renderLanes);<br>  }<br> ...<br>}</pre><pre>case SuspenseComponent:<br>      return updateSuspenseComponent(current, workInProgress, renderLanes);</pre><h4>updateSuspenseComponent</h4><p>updateSuspenseComponent는 크게 두 가지 부분으로 구성됩니다. 조건에 맞추어 “showFallback” 이라는 매우 직관적인 이름을 가진 플래그를 처리하는 부분과, 이 플래그를 기준으로 Fallback UI를 보여줄 것인지, Child Component UI를 보여줄 것인지를 결정하는 부분입니다.</p><p>먼저 플래그를 처리하는 부분을 살펴보겠습니다. showFallback 이라는 플래그는 didSuspend와 shouldRemainOnFallback 이라는 함수의 리턴값을 기준으로 해당 Suspense 컴포넌트의 Fallback UI 렌더링 여부를 결정합니다. 간단하게 설명하면, <em>didSuspend라는 플래그는 현재 Suspense 컴포넌트가 비동기 데이터를 가져오는 동안에 발생한 Suspend를 캡쳐했는지</em>, (즉 로딩중인지) 를 나타내는 bit flag 입니다. (해당 flag를 잡기 위해 bitwise 연산을 수행하는 것을 볼 수 있습니다.) <em>shouldRemainOnFallback은 Suspense 컴포넌트가 여전히 fallback 상태로 남아 있어야 하는지를 결정하며, 비동기 데이터 요청이 완료되었더라도 다른 우선순위가 더 높은 업데이트로 인해 아직 fallback 상태를 유지해야 하는 경우 true로 설정</em>됩니다.(Concurrent React..!)</p><pre>function updateSuspenseComponent(current, workInProgress, renderLanes) {<br>  const nextProps = workInProgress.pendingProps;<br>  <br>  let showFallback = false;<br>  const didSuspend = (workInProgress.flags &amp; DidCapture) !== NoFlags;<br>  if (<br>    didSuspend ||<br>    shouldRemainOnFallback(current, workInProgress, renderLanes)<br>  ) {<br>    // Something in this boundary&#39;s subtree already suspended. Switch to<br>    // rendering the fallback children.<br>    showFallback = true;<br>    workInProgress.flags &amp;= ~DidCapture;<br>  }<br>....</pre><p>다음으로는 플래그를 기준으로 Fallback UI를 보여줄 것인지, Child Component UI를 보여줄 것인지를 결정하는 부분을 살펴보겠습니다. (current === null 인 경우는 mount phase, current !== null 인 경우는 update phase라는 의미입니다.) 위의 로직에서 결정한 showFallback이 true인 경우, mountSuspenseFallbackChildren을 호출하고, false인 경우 mountSuspensePrimaryChildren을 호출하는 것을 확인할 수 있습니다.</p><pre>if (current === null) {<br>    // Initial mount<br>    const nextPrimaryChildren = nextProps.children;<br>    const nextFallbackChildren = nextProps.fallback;<br><br>    if (showFallback) {<br>      pushFallbackTreeSuspenseHandler(workInProgress);<br>      const fallbackFragment = mountSuspenseFallbackChildren(<br>        workInProgress,<br>        nextPrimaryChildren,<br>        nextFallbackChildren,<br>        renderLanes,<br>      );<br>      <br>      const primaryChildFragment: Fiber = (workInProgress.child: any);<br>      primaryChildFragment.memoizedState = mountSuspenseOffscreenState(<br>        renderLanes,<br>      );<br>      <br>      workInProgress.memoizedState = SUSPENDED_MARKER;<br>      return fallbackFragment;<br>    } else {<br>      pushPrimaryTreeSuspenseHandler(workInProgress);<br>      return mountSuspensePrimaryChildren(<br>        workInProgress,<br>        nextPrimaryChildren,<br>        renderLanes,<br>      );<br>    }<br>  }</pre><h4>mountSuspenseFallbackChildren</h4><p>mountSuspenseFallbackChildren은 실제로 Fallback UI와 Child Component를 모두 렌더링합니다. 이때 Fallback UI는 createFiberFromFragment를 사용해서 렌더링하고, Child Component는 mountWorkInProgressOffscreenFiber를 사용해서 렌더링하는데, 이때 들어가는 primaryChildProps의 mode 속성이 ‘hidden’으로 설정됩니다. 이는 Suspense 렌더링에서 핵심적인 부분을 담당하는데, DOM에는 반영되지 않지만(실제로 해당 노드는 display:none!important가 걸린 div로 업데이트되어 DOM에 나타나지 않습니다.), 백그라운드에서 해당 컴포넌트가 렌더링되어 실제 Data fetching과 reconcilation 대상이 되는 것입니다.</p><pre>function mountSuspenseFallbackChildren(<br>  workInProgress,<br>  primaryChildren,<br>  fallbackChildren,<br>  renderLanes,<br>) {<br>  const mode = workInProgress.mode;<br>  const progressedPrimaryFragment: Fiber | null = workInProgress.child;<br><br>  const primaryChildProps: OffscreenProps = {<br>    mode: &#39;hidden&#39;,<br>    children: primaryChildren,<br>  };<br>  let primaryChildFragment;<br>  let fallbackChildFragment;<br>  primaryChildFragment = mountWorkInProgressOffscreenFiber(<br>     primaryChildProps,<br>     mode,<br>     NoLanes,<br>  );<br>  fallbackChildFragment = createFiberFromFragment(<br>     fallbackChildren,<br>     mode,<br>     renderLanes,<br>     null,<br>  );<br>  primaryChildFragment.return = workInProgress;<br>  fallbackChildFragment.return = workInProgress;<br>  primaryChildFragment.sibling = fallbackChildFragment;<br>  workInProgress.child = primaryChildFragment;<br>  return fallbackChildFragment;<br>}</pre><pre>export function hideInstance(instance: Instance): void {<br>  // TODO: Does this work for all element types? What about MathML? Should we<br>  // pass host context to this method?<br>  instance = ((instance: any): HTMLElement);<br>  const style = instance.style;<br>  // $FlowFixMe[method-unbinding]<br>  if (typeof style.setProperty === &#39;function&#39;) {<br>    style.setProperty(&#39;display&#39;, &#39;none&#39;, &#39;important&#39;);<br>  } else {<br>    style.display = &#39;none&#39;;<br>  }<br>}</pre><h4>mountSuspensePrimaryChildren</h4><p>컴포넌트 렌더링을 위한 모든 데이터가 준비되고 충분한 렌더링 우선순위를 확보하게 되면, showFallback 플래그는 false로 바뀌게 되고, mountSuspensePrimaryChildren 에서는 mode: ‘visible’를 속성으로 해서 다시 mountWorkInProgressOffscreenFiber를 통해 ChildComponent를 렌더링합니다.</p><pre>function mountSuspensePrimaryChildren(<br>  workInProgress,<br>  primaryChildren,<br>  renderLanes,<br>) {<br>  const mode = workInProgress.mode;<br>  const primaryChildProps: OffscreenProps = {<br>    mode: &#39;visible&#39;,<br>    children: primaryChildren,<br>  };<br>  const primaryChildFragment = mountWorkInProgressOffscreenFiber(<br>    primaryChildProps,<br>    mode,<br>    renderLanes,<br>  );<br>  primaryChildFragment.return = workInProgress;<br>  workInProgress.child = primaryChildFragment;<br>  return primaryChildFragment;<br>}</pre><pre>function mountWorkInProgressOffscreenFiber(<br>  offscreenProps: OffscreenProps,<br>  mode: TypeOfMode,<br>  renderLanes: Lanes,<br>) {<br>  // The props argument to `createFiberFromOffscreen` is `any` typed, so we use<br>  // this wrapper function to constrain it.<br>  return createFiberFromOffscreen(offscreenProps, mode, NoLanes, null);<br>}<br>export function createFiberFromOffscreen(<br>  pendingProps: OffscreenProps,<br>  mode: TypeOfMode,<br>  lanes: Lanes,<br>  key: null | string,<br>) {<br>  const fiber = createFiber(OffscreenComponent, pendingProps, key, mode);<br>  fiber.elementType = REACT_OFFSCREEN_TYPE;<br>  fiber.lanes = lanes;<br>  const primaryChildInstance: OffscreenInstance = {<br>    visibility: OffscreenVisible,<br>    pendingMarkers: null,<br>    retryCache: null,<br>    transitions: null,<br>  };<br>  fiber.stateNode = primaryChildInstance;<br>  return fiber;<br>}</pre><h3>Handling promise</h3><p>다음은 ChildComponent가 데이터를 가져오는 동안 Suspense가 이를 Capture해서 showFallback을 true로 바꾸기 위해 어떤 일들이 일어나는가에 대한 부분입니다. Suspense의 개념적 모델을 다룬 이전 포스팅에서도 간단히 살펴보았듯, ChildComponent에서 데이터를 가져오는 promise를 throw하면, Suspense에서 이를 잡아 resolve한 후, 다시 제어권을 ChildComponent로 넘기는 방식으로 진행되므로 이 throw된 Promise를 처리하는 부분의 로직을 살펴보아야 할 것입니다. (promise를 던지는 data fetching 로직은 글 서두에 언급했던 예제를 확인해주세요.)</p><p>우선 다시 renderRootConcurrent로 돌아가겠습니다. 각 Fiber를 돌면서 렌더링을 처리하는 <strong><em>workLoopConcurrent라는 로직의 호출부를 try / catch로 한번 감싸고, do / while loop으로 한번 더 감싼 것</em></strong>을 확인할 수 있습니다. try / catch는 workLoopConcurrent에서 각 Fiber를 렌더링하기 위해 beginWork를 처리하는데, 이때 Error나 Promise를 throw하는 경우, 이를 catch해서 처리하기 위한 로직(handleError)이며, do / while loop은 promise가 throw된 경우, 이를 기다리기 위한 로직입니다.</p><pre>outer: do {<br>    try {<br>      if (<br>        workInProgressSuspendedReason !== NotSuspended &amp;&amp;<br>        workInProgress !== null<br>      ) {<br>        // The work loop is suspended. We need to either unwind the stack or<br>        // replay the suspended component.<br>        const unitOfWork = workInProgress;<br>        const thrownValue = workInProgressThrownValue;<br>        switch (workInProgressSuspendedReason) {<br>          case SuspendedOnError: {<br>            // Unwind then continue with the normal work loop.<br>            workInProgressSuspendedReason = NotSuspended;<br>            workInProgressThrownValue = null;<br>            unwindSuspendedUnitOfWork(unitOfWork, thrownValue);<br>            break;<br>          }<br>          case SuspendedOnData: {<br>            const thenable: Thenable&lt;mixed&gt; = (thrownValue: any);<br>            if (isThenableResolved(thenable)) {<br>              // The data resolved. Try rendering the component again.<br>              workInProgressSuspendedReason = NotSuspended;<br>              workInProgressThrownValue = null;<br>              replaySuspendedUnitOfWork(unitOfWork);<br>              break;<br>            }<br>            // The work loop is suspended on data. We should wait for it to<br>            // resolve before continuing to render.<br>            const onResolution = () =&gt; {<br>              ensureRootIsScheduled(root, now());<br>            };<br>            thenable.then(onResolution, onResolution);<br>            break outer;<br>          }<br>	...<br>        }<br>      }<br>      workLoopConcurrent();<br>      break;<br>    } catch (thrownValue) {<br>      handleThrow(root, thrownValue);<br>    }<br>  } while (true);</pre><h4>handleThrow</h4><p>handleThrow에서는 workLoopConcurrent에서 throw한 것이 SuspenseException 이라는 특별한 값인 경우, thrownValue를 thenable로 만들고 workInProgressSuspendedReason을 SuspendedOnData라는 값으로 설정함으로써, 위의 do / while loop에서 이를 처리할 수 있도록 해줍니다.</p><pre>function handleThrow(root, thrownValue): void {<br>  // A component threw an exception. Usually this is because it suspended, but<br>  // it also includes regular program errors.<br>  //<br>  // We&#39;re either going to unwind the stack to show a Suspense or error<br>  // boundary, or we&#39;re going to replay the component again. Like after a<br>  // promise resolves.<br>  //<br>  // Until we decide whether we&#39;re going to unwind or replay, we should preserve<br>  // the current state of the work loop without resetting anything.<br>  //<br>  // If we do decide to unwind the stack, module-level variables will be reset<br>  // in resetSuspendedWorkLoopOnUnwind.<br>  // These should be reset immediately because they&#39;re only supposed to be set<br>  // when React is executing user code.<br>  resetHooksAfterThrow();<br>  resetCurrentDebugFiberInDEV();<br>  ReactCurrentOwner.current = null;<br>  if (thrownValue === SuspenseException) {<br>    // This is a special type of exception used for Suspense. For historical<br>    // reasons, the rest of the Suspense implementation expects the thrown value<br>    // to be a thenable, because before `use` existed that was the (unstable)<br>    // API for suspending. This implementation detail can change later, once we<br>    // deprecate the old API in favor of `use`.<br>    thrownValue = getSuspendedThenable();<br>    workInProgressSuspendedReason = shouldAttemptToSuspendUntilDataResolves()<br>      ? SuspendedOnData<br>      : SuspendedOnImmediate;<br>  }<br> ...<br>  workInProgressThrownValue = thrownValue;<br>  ...<br>}</pre><h4>do / while loop</h4><p>do / while loop에서는 이 값을 thenable로 받아서 .then으로 이 값을 resolve하고, resolve가 다 된 이후에는 resolve가 된 시점을 기준으로 다시 스케줄러에 task를 등록함으로써 Suspense가 Child Component를 렌더링할 수 있도록 스케줄링 합니다. 이렇게 함으로써 Suspense는 promise가 throw된 경우 이를 catch해서 do / while loop을 돌면서 이 promise를 기다리고, promise가 resolve 될때까지 해당 renderRootConcurrent를 기다리게 했다가 resolve가 되면 다시 새로운 task를 스케줄러에 등록하도록 하는 식으로 promise를 처리합니다.</p><pre>case SuspendedOnData: {<br>    const thenable: Thenable&lt;mixed&gt; = (thrownValue: any);<br>    if (isThenableResolved(thenable)) {<br>      // The data resolved. Try rendering the component again.<br>      workInProgressSuspendedReason = NotSuspended;<br>      workInProgressThrownValue = null;<br>      replaySuspendedUnitOfWork(unitOfWork);<br>      break;<br>    }<br>    // The work loop is suspended on data. We should wait for it to<br>    // resolve before continuing to render.<br>    const onResolution = () =&gt; {<br>      ensureRootIsScheduled(root, now());<br>    };<br>    thenable.then(onResolution, onResolution);<br>    break outer;<br>}</pre><h3>Conclusion</h3><p>지금까지 여러 차례에 걸쳐 Suspense의 개념적 모델과 대수적 효과, 그리고 React Team 이 바라보는 Suspense의 모습과(SSR Architecture) Concurrent React에서의 Implementation에 대해 살펴보았습니다. Concurrent Mode에서의 Suspense는 단순히 로딩 UI를 보여주기 위한 것이 아닌 React의 철학(선언형 UI 라이브러리로서의 React)이 녹아들어있는 핵심적인 로직을 담당합니다.</p><ul><li><a href="https://yeoulcoding.me/328">Conceptual Model of React Suspense</a></li><li><a href="https://yeoulcoding.me/331">Algebraic Effects of React Suspense</a></li><li><a href="https://yeoulcoding.me/333">Suspense SSR Architecture in React 18</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e766582a7366" width="1" height="1" alt=""><hr><p><a href="https://blog.mathpresso.com/suspense-deep-dive-code-implementation-e766582a7366">Suspense Deep Dive (Code Implementation)</a> was originally published in <a href="https://blog.mathpresso.com/">Team QANDA</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modern Frontend Infrastructure Overview]]></title>
            <link>https://blog.mathpresso.com/modern-frontend-infrastructure-overview-99b5a8c669df?source=rss-9ce465f93d9e------2</link>
            <guid isPermaLink="false">https://medium.com/p/99b5a8c669df</guid>
            <category><![CDATA[infrastructure]]></category>
            <category><![CDATA[febe]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Yeoul]]></dc:creator>
            <pubDate>Sun, 12 Feb 2023 06:07:39 GMT</pubDate>
            <atom:updated>2023-02-24T09:13:00.647Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z2gcB46KgxTZ2lU8yDPmCg.png" /></figure><h3>Overview</h3><p>2022년, 모던 프론트엔드 개발 생태계를 주도하고 있는 React와 Next는 각각 새로운 Major 버전(React 18, Next13)을 Release 했습니다. React18에서는 Server Component와 Streaming HTML이라는 개념이 등장했고, 이를 FrameWork Level에서 지원하기 위해 Next13에서는 (아직은 Beta 버전인) <a href="https://beta.nextjs.org/docs/app-directory-roadmap">App Directory</a>라는 개념을 선보였습니다. 이 기능이 출시되자마자 이를 바로 작은 프로젝트에 적용해 보시면서 Pros / Cons를 이야기해 주시는 사내 시니어 프론트엔드 개발자분의 이야기를 듣다가. “어 그러면 기존의 React Application Component 일부분이 Server Component로 대체되면 기존보다 서버 요청이 많아지는 건가?, 그러면 성능은 좋아지더라도 우리 서버에 부담이 생기는 거 아닌가?” 하는 생각이 들었고 이를 직접 확인해 보고 싶은 생각이 들었습니다.</p><p>“우리 서버에 부담이 생기지 않는가?”를 확인하기 위해서는 현재 사내의 서비스 인프라 구조에서 클라이언트의 요청이 어디를 어떻게 지나 어디 어디에서 캐싱이 되고, 서버에 도달하는지에 대한 전반적인 흐름을 이해해야 하고, 실제로 각 지점을 지나는 트래픽을 모니터링할 수 있어야 합니다. 앞으로 이런 식의 궁금증을 해결할 일이 많을 것 같아서 이번 기회에 이 구조를 직접 구성해 팀원들에게 IaaC(Infrastructure as a Code) 형태로 전달하고, 각자가 자신의 playground에서 이를 테스트해 볼 수 있도록 만들어 제공하면 좋겠다고 생각했습니다.</p><p>이번 포스팅은 이러한 Background를 바탕으로 <strong><em>프론트엔드 개발자가 알아두면 좋을 Micro Service Architecture에 대한 고수준의 개요를 다룹니다</em></strong>. 고수준의 개요란, 아래에서 소개할 인프라를 구성하는 각 컴포넌트들을 이해하기 위해 필요한 지식들은 그 범위가 상당히 넓고 깊기 때문에 모든 디테일을 다 다루지 않고, 각 컴포넌트들에 대한 가벼운 개요와 컴포넌트들이 어떻게 연결되어 애플리케이션과 모니터링 시스템을 구성하는지에 초점을 맞추었다는 것을 의미합니다. 서비스를 구성하는 각 구성 요소들에 대한 구체적인 내용들은 아래 Reference 섹션에 작성된 각 서비스의 공식 문서를 참고해 주세요.</p><h3>Overall Structure</h3><p>이번 글을 통해 구성할 아키텍처는 다음과 같은 구성을 띱니다. 클러스터는 GKE 환경(<a href="https://cloud.google.com/kubernetes-engine/docs">Google Kubernetes Engine</a>)을 통해 구성하였고, 테스트를 위한 next13-demo 서비스의 container 이미지는 <a href="https://cloud.google.com/container-registry/docs">Google Container Registry</a>에 저장해 두었습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rWMj8gNQXhZor4yB.png" /></figure><p>위 구조에서 클러스터는 2개의 endpoint를 External Load Balancer의 형태로 클라이언트에게 오픈합니다. 하나는 next13-demo 애플리케이션으로 진입할 수 있는 엔트리포인트인 <strong><em>istio ingress gateway의 endpoint</em></strong>이고, 다른 하나는 next13-demo, kong-gateway, istio-ingress-gateway로 들어오는 각 네트워크 트래픽을 모니터링할 수 있는 <strong><em>grafana dashboard의 endpoint</em></strong>입니다. 위 구조에서 Application으로 들어오는 모든 트래픽은 istio ingress gateway를 지나 kong-gateway를 거쳐 각 Application 서비스(여기서는 next13-demo)로 들어가게 되며, 트래픽에 대한 정보(Latency, Respionse Code, Request Duration…)는 Grafana dashboard를 통해 확인할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/0*Nvp889kzuzIVrPYP.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Lg6KHnW3tGh3iX95.png" /></figure><p>이제부터 위의 Architecture를 구성하는 주요 개념들을 가볍게 살펴보고, 이들이 구체적으로 어떻게 연결되어 위의 구조를 만들어내는지를 살펴보도록 하겠습니다. 아래의 예시는 github의 데모에 코드로 올려두었습니다.</p><p><a href="https://github.com/sckimynwa/gitops-demo">GitHub - sckimynwa/gitops-demo</a></p><h3>CNCF</h3><p>CNCF(Cloud Native Computing Foundation)은 클라우드 환경에서 여러 조직들이 Scalable 한 애플리케이션을 구축하고 운영하기 위한 에코시스템을 만드는 것을 Mission으로 삼는 리눅스 재단 소속의 비영리 단체입니다. 컴포넌트 설명에 앞서 CNCF를 먼저 언급한 이유는 클라우드 환경에서 인프라를 구축하기 위한 여러 프로젝트들(Kubernetes, Argocd, Istio, Terraform, Kong)이 전부 이 CNCF의 프로젝트들이기 때문입니다. 위의 서비스 아키텍처를 구성하는 여러 컴포넌트들도 전부 이 CNCF 프로젝트의 결과물들이기 때문에 모던 클라우드 시스템이 어떤 방향으로 흘러가는지를 이해하기 위해서는 CNCF의 프로젝트들을 주의 깊게 살펴보는 것이 좋습니다.</p><blockquote><em>The Foundation’s mission is to make cloud native computing ubiquitous. The CNCF Cloud Native Definition v1.0 says: Cloud native technologies </em><strong><em>empower organizations to build and run scalable applications in modern, dynamic environments</em></strong><em> such as public, private, and hybrid clouds.</em><strong><em> Containers, service meshes, microservices, immutable infrastructure, and declarative APIs exemplify this approach</em></strong><em>. — CNCF</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w_xQM6805fhJlQN-.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5Um6cwsR8cGEG-TM.png" /></figure><h3>Terraform</h3><p>클라우드 환경에서 복잡한 애플리케이션 시스템을 운영하기 위해서는 클라우드 환경의 많은 컴포넌트들과 IAM들을 설정하고 관리해야 합니다. 당장 위의 예제와 같이 간단한 인프라 구조의 애플리케이션을 만들 때는 직접 하나하나 콘솔에서 설정해 주어도 되지만, 콘솔이나 기본적인 CLI를 가지고 수백 명의 구성원들에 대한 권한 관리와, 수백 개가 넘는 컴포넌트들을 관리하는 것은 정확성이 떨어질뿐더러 시간도 오래 걸린다는 점에서 비효율적입니다.</p><p>Terraform은 이러한 문제를 해결하기 위해 Infrastructure as a Code(IaaC) 개념을 구현한 소프트웨어입니다. IaaC란 인프라의 구성을 코드로 관리하겠다는 뜻으로, 내가 원하는 인프라의 상태(e.g cluster-yeoul이라는 클러스터를 하나 만들건데, Location은 asia-northeast3-c이고, node는 3개, memory는 2개로 하고, 이러한 권한을 주고, 또 Container Registry도 하나 만들 거고, GCLB도 이러한 구성으로 하나 만들 거야)를 코드로 기술하면 소프트웨어가 이 코드에 맞는 인프라를 벤더(Google Cloud, AWS, Azure..)에 구축하는 책임을 집니다.</p><p>Terraform은 인프라 구조를 “선언형”으로 관리함으로써 해당 인프라를 코드에 쓰인 그대로 유지할 책임을 소프트웨어에 넘기고 인프라를 관리하는 DevOps Engineer로 하여금 효과적인 구조 설계와 권한 관리에 집중할 수 있도록 도와줍니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8V_jMiQS2RvrJ9IE.png" /></figure><p>위 예제에서도 GKE Cluster의 설정을 관리하기 위해(사실은 GKE는 띄워두면 비용이 많이 들어서 편하게 띄웠다 지웠다 할 수 있도록 하기 위해서 Terraform을 썼습니다.) Terraform으로 IaC(Infrastructure as a Code)를 구성하였으며, 코드는 아래와 같습니다. 로컬 환경에 클러스터를 생성하고자 하는 프로젝트의 application default 권한을 설정하고 (<em>gcloud application default login</em>) terraform을 설치한 뒤 terraform apply를 입력하면 아래와 같이 cluster-yeoul이라는 이름의 쿠버네티스 클러스터가 생성됩니다. (terraform에 대한 자세한 내용과 다른 기능들에 대한 내용은 <a href="https://developer.hashicorp.com/terraform/intro">공식 문서</a>를 참고해 주세요)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pg4YLjnsuCMRBwxa.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wpj0FL5PJ3pzl5-a.png" /></figure><p><a href="https://developer.hashicorp.com/terraform/downloads">Install | Terraform | HashiCorp Developer</a></p><h3>Kubernetes(K8S)</h3><blockquote><em>Kubernetes, also known as K8s, is an open-source system for automating deployment, scaling, and management of containerized applications.</em></blockquote><p>클라우드 환경에서 서비스되는 애플리케이션은 대부분 Image의 형태로 빌드되며, 컨테이너에서 이 이미지를 실행하는 구조를 갖습니다. (App Engine, Cloud Run과 같은 예외 케이스들도 있긴 합니다.) 위의 예제에서도 <a href="https://github.com/sckimynwa/next13-demo">next13-demo라는</a> 애플리케이션을 빌드하면 아래의 Dockerfile대로 빌드되어 도커 이미지가 생성되며, Container Registry에 저장된 이 이미지는 실행되어 컨테이너 런타임 환경에서 서비스됩니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/0*jJWBaITdxGStr3Jt.png" /></figure><p>수백 ~ 수천 개의 서비스들이 제공되는 복잡한 애플리케이션은 그만큼 저장해야 하는 이미지도 많으며, 많은 트래픽을 받는 서비스의 경우 유연하게 Horizontal, Vertical Scaling도 할 수 있어야 합니다. 게다가 오류 발생, 트래픽 과다 등의 이유로 컨테이너가 서비스할 수 없게 되면 적절한 health check를 통해 이를 재시작해주어야 하고, 최신 버전에서 버그가 발생했을 때 이를 빠르게 롤백해 주는 등의 작업도 필요합니다. 이렇게 애플리케이션을 서비스하는 여러 개의 컨테이너들을 다루는 전반적인 과정을 일컬어 Container Orchestration이라 하며 쿠버네티스는 이 Container Orchestration을 선언적으로 수행할 수 있도록 도와주는 소프트웨어입니다. (공식 문서: <a href="https://kubernetes.io/docs/concepts/">What is Kubernetes?</a>)</p><p>쿠버네티스에 대한 기본 개념과 아이디어, 구조 등은 이번 글의 범위를 벗어나므로 다루지는 않겠습니다. 다만 이에 대한 기본적인 이해가 있어야 이후 소개할 Helm Charts, Istio, Prometheus, Grafana에 대한 연관관계와 구조를 이해할 수 있는데, 이 컴포넌트들이 모두 쿠버네티스의 리소스를 다루거나(Helm Charts), 쿠버네티스 안에서 서비스되는 파드나 서비스(Istio, Prometheus, Grafana)의 형태로 구성되어 동작하기 때문입니다. 따라서 <a href="https://kubernetes.io/docs/concepts/overview/">Kubernetes가 무엇인지</a>, 그리고 이를 구성하는 요소 중에 <a href="https://kubernetes.io/docs/concepts/workloads/pods/">Pod</a>, <a href="https://kubernetes.io/docs/concepts/services-networking/">Service</a>, <a href="https://kubernetes.io/docs/concepts/workloads/controllers/deployment/">Deployment</a>와 같은 개념들은 각각 무엇을 의미하는지를 먼저 이해하신 후에 이후 내용으로 넘어갈 것을 권장합니다.</p><p>쿠버네티스에 대한 자세한 내용은 공식 문서를 참고해 주세요. 혹은 이 블로그에서 <a href="https://yeoulcoding.me/221">Kubernetes in Action을 정리한 포스팅 시리즈</a>를 참고하셔도 좋습니다.</p><p><a href="https://kubernetes.io/releases/download/">Download Kubernetes</a></p><h3>Helm Charts</h3><blockquote><em>Helm uses a packaging format called charts. A chart is a collection of files that describe a related set of Kubernetes resources. A single chart might be used to deploy something simple, like a memcached pod, or something complex, like a full web app stack with HTTP servers, databases, caches, and so on.</em></blockquote><p>Helm 공식 문서에는 Helm을 “<strong><em>The package manager for Kubernetes</em></strong>”라고 소개하고 있습니다. 우리에게 익숙한 Package Manager로는 npm, yarn, pnpm 등이 있는데, 이들이 의미 있는 js 코드의 묶음(우리가 라이브러리라고 부르는)을 “패키지 단위”로 “버저닝 하여” 관리할 수 있도록 도와주는 기능을 제공하듯이, Helm도 의미 있는 쿠버네티스의 리소스의 묶음을 하나의 “패키지 단위”로 “버저닝 하여” 관리할 수 있도록 도와주는 기능을 제공합니다.</p><p><em>“yarn add react”라는</em> 명령어를 치면 로컬 디렉터리에 react라는 라이브러리가 node_module의 형태로 설치되듯이 “<em>helm install next13-demo next13-demo”라는</em> 명령어를 치면 클러스터에 next13-demo 애플리케이션을 구성하기 위한 service, pod, serviceaccount 등의 리소스들이 설치됩니다.</p><p>이해를 돕기 위해 next13-demo 애플리케이션을 살펴보도록 하겠습니다. next13-demo 애플리케이션은 CI/CD 파이프라인을 통해 docker image의 형태로 Container Registry에 빌드되어 올라갑니다. 그러면 이 이미지는 쿠버네티스에서 관리하는 가장 작은 단위인 파드 안에 컨테이너의 형태로 실행됩니다. 애플리케이션은 파드 안의 컨테이너이지만, 실제로 쿠버네티스에서는 Load Balancing, Horizontal Scaling, Namespace Separation 등을 지원하기 위해 파드 하나만 떠있는 형태가 아닌, 아래와 같이 Service, Deployment, Namespace, ServiceAccount 등 다른 많은 Kubernetes Resource 등을 필요로 하게 됩니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/0*ujU1qlLIbLByRhQl.png" /></figure><p>이렇게 하나의 애플리케이션에 대해 관리해야 하는 리소스들이 많아지면 자연스럽게 중복해서 들어가는 요소들 (namespace나 image tag, servicename)이 생기게 되며, 버전 관리의 필요성도 생기게 됩니다. Helm Charts는 이를 아래와 같이 Template과 Values로 나누어서 패키지의 형태로 관리할 수 있도록 도와주고, Template이나 Values가 변경되었을 때, 이를 새로운 버전으로 관리할 수 있도록 도와줍니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/0*9j6ha4C5AucolSG0.png" /></figure><p>위의 이미지에서 볼 수 있듯이, next13-demo Application을 서비스하기 위해 deployment, hpa, namespace, service, serviceaccount의 리소스가 필요한 것을 알 수 있습니다. 위의 구성을 바탕으로 로컬에서 내 클러스터에 helm install을 한다는 것은 다음과 같은 의미를 갖습니다.</p><p>“클러스터의 next13-demo namespace에 next13-demo라는 helm package를 install 할 건데, 여기에는 deployment, hpa, namespace, service, serviceaccount의 리소스가 있고 각 리소스에 넣어야 하는 값은 values에 있으니까 찾아서 잘 채워 넣은 다음에 kubernetes에 리소스 생성해 줘”</p><p>만약 새로운 이미지가 업데이트되어 image tag가 변경되었다면 image tag를 사용하는 yaml 파일들을 일일이 수정하는 것이 아니라 values.yaml에서 image tag만 수정해 주고 다시 helm install을 하면 새로운 버전으로 chart가 업데이트되며, 새로운 애플리케이션이 서비스됩니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/0*Aa6cy-qCc65TYajO.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*llWeIxfYGvOVCl1n.png" /></figure><p><a href="https://helm.sh/docs/intro/install/">Installing Helm | Helm</a></p><h3>Istio</h3><p><a href="https://istio.io/latest/about/service-mesh/">istio 공식 문서</a>에서는 istio를 서비스 메시(Service Mesh)라고 소개하며, Service Mesh가 무엇인지에 대해서는 다음과 같이 이야기하고 있습니다. (Istio is an open source service mesh)</p><blockquote><em>Modern applications are typically architected as distributed collections of microservices, with each collection of microservices performing some discrete business function.</em></blockquote><blockquote><strong><em>A service mesh is a dedicated infrastructure layer that you can add to your applications</em></strong><em>. It allows you to transparently add capabilities like observability, traffic management, and security, </em><strong><em>without adding them to your own code</em></strong><em>. The term “service mesh” describes both the type of software you use to implement this pattern, and the security or network domain that is created when you use that software.</em></blockquote><p>위 설명에 따르면 서비스 메시란, <strong><em>애플리케이션 코드에 추가적인 수정을 하지 않고 observability, traffic management, security를 제공할 수 있도록 만든 추가적인 인프라 레이어</em></strong>를 이야기합니다. 서비스 메시 없이 100개의 애플리케이션에 일괄적으로 모니터링 툴을 붙이고 싶은 경우 각 애플리케이션 코드에 이를 지원하는 코드를 추가한 후 모두 다시 재배포해야 하지만, 서비스 메시를 사용하는 경우, 애플리케이션 코드 수정 없이 별도의 인프라 레이어에서 이를 지원할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*u6C-X_HSfWE14FDB.png" /></figure><p>istio는 이 서비스 메시를 <strong><em>사이드카 패턴(Sidecar)</em></strong>을 사용해서 지원합니다. 즉 하나의 파드에 애플리케이션 컨테이너 하나, istio-proxy 컨테이너 하나가 들어가게 되며, 애플리케이션 컨테이너로 들어오는 모든 트래픽은 우선 istio-proxy 컨테이너를 거쳐 애플리케이션 컨테이너로 들어가고, 다시 istio-proxy 컨테이너를 거쳐 바깥으로 나가게 됩니다.</p><p>이렇게 모든 ingress / egress 트래픽이 istio-proxy를 거치게 되고 이 트래픽들은 모두 istio control plane(istiod)에 의해 접근할 수 있는 상태가 됩니다. 따라서 애플리케이션의 수정 없이 istio-proxy를 거치는 트래픽들을 모니터링함으로써 애플리케이션이 정상인지, latency는 얼마나 되는지 등의 정보를 파악할 수 있으며 (실제로 이를 사용해서 dashboard를 구성하는 application이 아래에서 살펴볼 prometheus와 grafana입니다.) 이외에 추가적인 보안 설정이나 traffic management 같은 기능들도 별도의 레이어에서 구현할 수 있게 됩니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-nImQWMM5eawQtr6.png" /></figure><p>클러스터에 istio를 구성하는 방법은 다음과 같습니다. (복잡한 설정을 최대한 피하기 위해 위에서 살펴보았던 helm chart를 사용해서 쿠버네티스 리소스를 생성하였습니다. 별도로 설정을 건드린 것은 istio ingress gateway에 대한 커스텀 설정이며, 그 외의 나머지 요소들은 istio에서 올려둔 remote helm charts를 다운받아 사용했습니다.)</p><pre># istio-system<br>kubectl create namespace istio-system<br>helm install istio-base istio/base -n istio-system <br>helm install istiod istio/istiod -n istio-system --wait</pre><pre># istio-ingress-gateway<br>kubectl create namespace istio-ingress<br>kubectl label namespace istio-ingress istio-injection=enabled<br>helm install istio-ingress istio/gateway -n istio-ingress --wait<br>kubectl apply -f ./istio/gateway.yaml</pre><p>주목할 만한 점은, istio-ingress namespace와 next13-demo namespace에 istio-injection=enabled라는 label이 붙어있는데, 이는 istio에서 <strong><em>이러한 label이 붙어있는 namespace에서 생성되는 pod에 자동으로 istio-proxy container를 주입해 주기 때문</em></strong>입니다. 따라서 위와 같이 istio-system을 클러스터에 설치했다면, 파드가 생성될 namespace에 다음과 같이 label만 붙여주어도 해당 namespace에 있는 파드의 ingress/egress traffic을 istio를 통해 조회할 수 있게 됩니다.</p><blockquote><em>When you set the istio-injection=enabled label on a namespace and the injection webhook is enabled, </em><strong><em>any new pods that are created in that namespace will automatically have a sidecar added to them</em></strong><em>.<br>Note that unlike manual injection,</em><strong><em> automatic injection occurs at the pod-level</em></strong><em>. You won’t see any change to the deployment itself. Instead, you’ll want to check individual pods (via kubectl describe) to see the injected proxy.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/0*fFhJ-Nm21E1Oq5PH.png" /></figure><p>추가적으로 위의 Shell Command에서 istio-system 서비스뿐만 아니라 istio-ingress-gateway 서비스도 클러스터 내에 설치하고 있는 것을 확인할 수 있는데 istio-ingress-gateway는 파드 내에 istio-proxy 컨테이너 하나 존재하는 gateway 리소스로, 애플리케이션 파드 내에 들어가는 istio-proxy 파드가 애플리케이션으로 들어오고 나가는 트래픽을 모니터링하는 것과 다르게 클러스터 내로 직접 들어오는 파드를 모니터링하면서 뒷단의 서비스로 트래픽을 흘려보내는 Gateway 역할까지 수행하게 됩니다.</p><p>위의 예제는 kong-gateway 한 군데로 트래픽을 보내고, Kong-Gateway가 path를 보고 뒷단의 서비스로 routing 하는 구조로 구성되어 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-ZDIzhGy0qm1A0Vk.png" /></figure><blockquote><em>Along with support for Kubernetes Ingress resources, Istio also allows you to configure ingress traffic using either an Istio Gateway or Kubernetes Gateway resource. A Gateway provides more extensive customization and flexibility than Ingress, and </em><strong><em>allows Istio features such as monitoring and route rules to be applied to traffic entering the cluster</em></strong><em>.</em></blockquote><h3>Prometheus &amp; Grafana</h3><p>istio를 사용하면 각 애플리케이션 컨테이너에 대한 ingress / egress network traffic을 관리할 수 있습니다. 이를 조금 더 체계적으로 시각화해서 도와줄 수 있는 Tool이 바로 Prometheus와 Grafana입니다. Prometheus는 istio proxy container로부터 데이터를 주기적으로 가져와(scraping) 시계열 데이터를 처리하기에 적절한 포맷으로 관리하고 Grafana는 API를 사용해서 이 데이터들을 적절하게 시각화해서 보여주는 역할을 하게 됩니다. 전체 구조는 다음과 같으며 구체적인 내용은 <a href="https://prometheus.io/docs/introduction/overview/">Prometheus</a>와 <a href="https://grafana.com/grafana/">Grafana</a>의 공식 문서를 참고해 주세요.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/0*oNKJ2guILXL60lSY.png" /></figure><p>주목할만한 점은 istio와 prometheus 간의 호환성입니다. istio에서는 설정을 단순화하기 위해(To simplify configuration) 프로메테우스와의 호환을 위한 여러 설정들을 default로 켜두었습니다. 따라서 istio를 사용하면 prometheus를 설치하는 것 만으로 istio-proxy의 데이터가 promethues와 연동되며 실제로 next13-demo의 파드 내의 Annotations를 보면 별도의 prometheus 설정을 하지 않았는데도 istio에서 proxy를 주입하면서 prometheus.io와 관련된 여러 annotations들을 추가해 준 것을 확인할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7_jnnHHdFwCHVt1c.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/0*sAWG_jEQBMZkf_oN.png" /></figure><p>예제에서는 별도로 grafana, premetheus에 대한 커스텀 설정을 하지 않았고, 공식문서에 나오는 기본적인 설정을 그대로 사용하였습니다. (추가적인 커스텀 설정이 필요하다면 grafana, prometheus에 대한 공식 문서를 참고해 주세요)</p><p><a href="https://raw.githubusercontent.com/istio/istio/release-1.16/samples/addons/grafana.yaml">https://raw.githubusercontent.com/istio/istio/release-1.16/samples/addons/grafana.yaml</a></p><p><a href="https://raw.githubusercontent.com/istio/istio/release-1.16/samples/addons/prometheus.yaml">https://raw.githubusercontent.com/istio/istio/release-1.16/samples/addons/prometheus.yaml</a></p><pre>kubectl apply -f ./grafana/prometheus.yaml<br>kubectl apply -f ./grafana/grafana.yaml</pre><p>두 yaml 파일을 적용하고 나면 다음과 같이 prometheus와 grafana service가 클러스터에 추가된 것을 확인할 수 있고 grafana dashboard아 external load balancer의 형태로 외부에서 접근할 수 있게 열려 있는 것을 확인할 수 있습니다. istio-ingress에 접근하여 next13-demo 애플리케이션 페이지에 접속한 뒤 몇 번 새로 고침 해서 트래픽을 주면 다음과 같이 istio-proxy container에 들어오는 트래픽들을 Grafana에서 Dashboard의 형태로 확인할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/919/0*25n1NJP4jE-z5ryP.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KA9MthvbOs4u_gGb.png" /></figure><h3>Bring them Alltogether</h3><p>조금은 긴 호흡으로 아키텍처를 이해하기 위한 개념들을 한번 살펴보았습니다. 이러한 개념들을 바탕으로 다시 처음의 Architecture Diagram을 확인해 보도록 하겠습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JX-So5i1sHrS5QXb.png" /></figure><p>클라이언트는 External LoadBalancer을 통해 외부에 노출된 Istio Ingress Gateway로 요청을 보내게 됩니다. (htpp://34.64.179.95:80) Istio Ingress Gateway는 이 요청을 받아 뒷단의 Kong Gateway로 요청을 흘려보내며, Kong Gateway는 이번 예제에서는 별다른 설정 없이 뒤의 next13-demo 서비스로 트래픽을 흘려줍니다.</p><p>next13-demo 서비스가 트래픽을 받으면 이 트래픽은 next13-demo 파드(들) 중 하나로 LoadBalancing 되어 들어가게 되며 파드로 들어간 트래픽은 istio-proxy를 지나 Application Container로 도달하게 됩니다. 요청을 처리한 뒤 Response는 다시 istio-proxy를 거쳐 Kong Gateway를 지나고 Istio Ingress Gateway를 지나 Client에 도달하게 됩니다.</p><p>이 과정에서 Istio Ingress Gateway와 Kong Gateway, 그리고 next13-demo 각각에 존재하는 istio-proxy 컨테이너에는 로그가 쌓이게 되며, 이 로그는 prometheus의 job에 의해 수집되고 Grafana Dashboard를 통해 보이게 됩니다.</p><p>중간에 kong-gateway의 내용이 있습니다. 이는 이후에 kong-gateway를 별도로 설명할 때 다루겠지만 뒷단의 여러 서비스들에 대해(지금은 next13-demo밖에 없지만, 앞으로 많은 서비스들이 붙을 수 있음) 인증을 처리하고 L7 Routing을 처리해 주는 Gateway의 역할을 수행합니다. 구체적인 내용에 대한 소개는 이 구조에서 백엔드 서비스를 추가하고 인증을 처리할 때 다시 다루도록 하겠습니다.</p><p>아래 Shell Script는 이 전체 구조를 만드는 데 필요한 Shell Script입니다.</p><pre>#!/bin/sh</pre><pre># Regular Colors<br>Black=&#39;\033[0;30m&#39;        # Black<br>Red=&#39;\033[0;31m&#39;          # Red<br>Green=&#39;\033[0;32m&#39;        # Green<br>Yellow=&#39;\033[0;33m&#39;       # Yellow<br>Blue=&#39;\033[0;34m&#39;         # Blue<br>Purple=&#39;\033[0;35m&#39;       # Purple<br>Cyan=&#39;\033[0;36m&#39;         # Cyan<br>White=&#39;\033[0;37m&#39;        # White<br>Nc=&#39;\033[0m&#39;</pre><pre>echo &quot;${Yello} Setup Start. ${Nc}\n&quot;</pre><pre>echo &quot;${Green}1. Gcloud Container ${Nc}\n&quot;<br>gcloud auth application-default login<br>gcloud container clusters get-credentials cluster-yeoul --region asia-northeast3-c</pre><pre>echo &quot;\n${Green}2. Istio Setting ${Nc}\n&quot;<br>kubectl create namespace istio-system<br>helm install istio-base istio/base -n istio-system <br>helm install istiod istio/istiod -n istio-system --wait</pre><pre>kubectl create namespace istio-ingress<br>kubectl label namespace istio-ingress istio-injection=enabled<br>helm install istio-ingress istio/gateway -n istio-ingress --wait<br>kubectl apply -f ./istio/gateway.yaml</pre><pre>echo &quot;\n${Green}3. Application Setting ${Nc}\n&quot;<br>kubectl create namespace kong-gateway<br>kubectl apply -k ./kong-gateway</pre><pre>helm install next13-demo next13-demo<br></pre><pre>echo &quot;\n${Green}4. Grafana Setting ${Nc}\n&quot;<br>kubectl apply -f ./grafana/prometheus.yaml<br>kubectl apply -f ./grafana/grafana.yaml</pre><pre>echo &quot;\n${Yello} Setup Finished. ${Nc}\n&quot;</pre><h3>Conclusion</h3><p>이 글을 작성한 이유는 위 아키텍처를 구성하는 각 개념(Kubernetes, Istio, Helm Chart…)을 상세하게 다루고 디테일을 챙기며 커스텀 설정 옵션을 알아보기 위한 것이 아닙니다. 각 개념은 각각 별도의 시리즈로 구성해야 할 만큼 히스토리가 길고 디테일이 많으며 글을 작성하는 지금 시점에서 저도 알지 못하는 내용이 많기 때문입니다.</p><p>다만, 개인적으로 이 아키텍처를 구성하면서 가장 힘들었던 점이 수많은 용어들과 개념들이 나오는데, 이 개념들이 각각 전체 그림에서 어떤 부분을 담당하고 있고, 어떤 개념들과 상호작용하며, 어떤 역할을 하는지를 파악하는 것이었기 때문에 이 부분에 대한 그림을 가볍게 소개하기 위한 목적에서 이 글을 작성하게 되었습니다.</p><p>성능 좋은 웹 애플리케이션을 제공하는 데 있어서 내가 만든 웹 애플리케이션이 어떤 경로를 거쳐서 서비스되는지를 알고 있으면, 보다 다양한 방법을 사용해 효율적으로 성능을 높일 수 있습니다. 이 글을 통해 개인적으로 기대하는 것은, 인프라 공부를 해야 하는 것은 알겠는데, 어디부터 어떻게 시작해야 하는지가 애매했던 프론트엔드 개발자분들에게 전반적인 밑그림을 제공하는 것입니다.</p><p>제가 테스트했던 예제 코드는 아래와 같습니다. 다만 학습하시는 입장에서 이 구조가 SOTA(State Of The Art)는 아니며, 학습하는 과정에 있어서 참고하는 정도로만 사용하시는 것을 권장합니다. 이 글을 기반으로 이어지는 이후 포스팅에서 각 컴포넌트에 대한 커스텀 설정들과 디테일들을 조금씩 다룰 예정입니다.</p><p><a href="https://github.com/sckimynwa/gitops-demo">GitHub - sckimynwa/gitops-demo</a></p><h3>Reference</h3><ul><li><a href="https://reactjs.org/blog/2022/03/29/react-v18.html">React v18.0 - React Blog</a></li><li><a href="https://nextjs.org/blog/next-13">Next.js 13</a></li><li><a href="https://developer.hashicorp.com/terraform/intro">What is Terraform | Terraform | HashiCorp Developer</a></li><li><a href="https://kubernetes.io/docs/concepts/">Concepts</a></li><li><a href="https://istio.io/latest/about/service-mesh/">The Istio service mesh</a></li><li><a href="https://prometheus.io/docs/introduction/overview/">Overview | Prometheus</a></li><li><a href="https://grafana.com/grafana/">Grafana | Query, visualize, alerting observability platform</a></li></ul><ul><li>🌏글로벌 Top 교육 앱 QANDA(콴다)를 함께 만들어 갈 Frontend개발자들을 기다리고 있습니다!</li><li>🖥️콴다 팀의 개발 문화가 궁금하다면? ➡️ <a href="https://www.youtube.com/watch?v=9Xtm92NAU58">Inside QANDA: 최고의 글로벌 교육 서비스를 개발한다는 것</a></li><li>🕹️콴다 Frontend Team은 채용 중 입니다!➡️ <a href="http://bit.ly/3pVjlmR">공고 확인하기</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99b5a8c669df" width="1" height="1" alt=""><hr><p><a href="https://blog.mathpresso.com/modern-frontend-infrastructure-overview-99b5a8c669df">Modern Frontend Infrastructure Overview</a> was originally published in <a href="https://blog.mathpresso.com/">Team QANDA</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How @next/font works]]></title>
            <link>https://blog.mathpresso.com/how-next-font-works-8bb72c2bae39?source=rss-9ce465f93d9e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8bb72c2bae39</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[febe]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Yeoul]]></dc:creator>
            <pubDate>Sun, 15 Jan 2023 21:34:21 GMT</pubDate>
            <atom:updated>2023-02-24T09:00:37.737Z</atom:updated>
            <content:encoded><![CDATA[<h4>Zero Layout Shift를 위한 Next Font Optimization의 원리</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mdlbLt56rwYKlXRZH7tJQw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Z6Us8QlfBWwuxsib.jpg" /></figure><h3>Overview</h3><blockquote><em>@next/font includes built-in automatic self-hosting for any font file. This means you can optimally load web fonts with zero layout shift, thanks to the underlying CSS size-adjust property used.</em></blockquote><blockquote><em>This new font system also allows you to conveniently use all Google Fonts with performance and privacy in mind. CSS and font files are downloaded at build time and self-hosted with the rest of your static assets. No requests are sent to Google by the browser. — next.js official docs</em></blockquote><p>next13이 소개되면서 @next/font라는 패키지가 새롭게 추가되었습니다. @next/font 패키지에는 빠른 font loading, 그리고 zero-layout shift를 지원하기 위한 adjustFallbackFont 등의 기능이 들어 있어서 사용자에게 네트워크 환경과 상관없이 최대한 일관적인 UX경험을 제공하는데 초점을 맞추고 있습니다.</p><p>지원하는 기능과 API에 대한 설명은 아래 Reference 섹션에 있는 next/font 공식 문서에서 최신의 문서를 살펴보시는 것이 좋으며, 이번 포스팅에서는 @next/font가 어떤 방식으로 폰트 최적화를 지원하는지에 대한 내용을 Source Code Level에서 간단하게 살펴보도록 하겠습니다. (FYI. @next/font는 @next/font/google과 @next/font/local이 있는데, 두 패키지 모두 동작원리는 비슷하고, 대부분의 프로젝트가 @next/font/google을 사용할 것으로 예상되므로, 이번 포스팅에서는 @next/font/google에 대해서만 다루도록 하겠습니다.)</p><h3>Examples</h3><p>소스 코드로 들어가 보기 전에, 실제로 기존 Next12에서의 폰트 로드와 Next13에서의 폰트 로드가 어떻게 바뀌었는지 실제 예시를 통해 살펴보도록 하겠습니다. 똑같이 32px이라는 font-size를 주더라도 폰트마다 실제로 렌더링 되는 사이즈가 조금씩 다르기 때문에 이 차이점을 잘 부각해 줄 수 있는 손글씨 폰트인 “Homemade Apple”이라는 Google Font를 통해 예시를 만들었습니다. 그리고, Layout Shift가 일어나는지의 여부를 확인하기 위해 텍스트 아래에 image component를 두어 실제로 이미지가 폰트 로딩에 따라 밀려나는지 여부를 확인할 수 있도록 예제를 구성했습니다. 예제 코드는 다음과 같습니다.</p><p><strong>Next 12 Test Code</strong></p><pre>import Head from &#39;next/head&#39;<br>import Image from &#39;next/image&#39;;<br>import Cat from &#39;../assets/images/cat.jpg&#39;;</pre><pre>export default function Home() {<br>  return (<br>    &lt;div&gt;<br>      &lt;Head&gt;<br>        &lt;title&gt;Font Test&lt;/title&gt;<br>        &lt;meta name=&quot;description&quot; content=&quot;Font Test&quot; /&gt;<br>        &lt;link rel=&quot;icon&quot; href=&quot;/favicon.ico&quot; /&gt;<br>        &lt;link rel=&quot;preconnect&quot; href=&quot;https://fonts.googleapis.com&quot;/&gt;<br>        &lt;link rel=&quot;preconnect&quot; href=&quot;https://fonts.gstatic.com&quot; crossorigin/&gt;<br>        &lt;link href=&quot;https://fonts.googleapis.com/css2?family=Homemade+Apple&amp;display=swap&quot; rel=&quot;stylesheet&quot;/&gt;<br>      &lt;/Head&gt;<br>      &lt;main&gt;<br>        Homemade Apple Font (Next 12)<br>        &lt;Image src={Cat} alt=&quot;cat&quot;/&gt;<br>      &lt;/main&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><p><strong>Next 13 Test Code</strong></p><pre>import { Homemade_Apple } from &#39;@next/font/google&#39;;<br>import Image from &#39;next/image&#39;;<br>import Cat from &#39;../assets/images/cat.jpg&#39;;</pre><pre>const homemadeApple = Homemade_Apple({ subsets: [&#39;latin&#39;], weight: [&#39;400&#39;], display: &#39;swap&#39; })<br><br>export default function Home() {<br>  return (<br>    &lt;main className={homemadeApple.className}&gt;<br>      Homemade Apple Font (Next 13)<br>      &lt;Image src={Cat} alt=&quot;cat&quot;/&gt;<br>    &lt;/main&gt;<br>  )<br>}</pre><h3>Zero Layout Shift</h3><p>우선은 Layout Shift에 관한 내용입니다. font-size를 동일하게 맞춰도, 각각의 폰트가 기본적으로 가지고 있는 크기가 조금씩 다르기 때문에 서로 다른 폰트를 교체하는 과정에서 Layout Shift가 발생합니다. (<a href="https://fonts.google.com/knowledge/glossary/fout">이를 FOUT, Flash Of Unstyled Text라고 합니다</a>.) Next 12에서는 이에 대해 별다른 처리를 하고 있지 않기 때문에 첫 번째 그림처럼, Homemade Apple 폰트가 로드되기 전에 기본적으로 보여주는 Font와 로드된 폰트의 크기가 달라서 폰트가 로드된 이후에 image가 아래로 밀려나는 Layout Shift가 발생하고 있는 것을 확인할 수 있습니다.</p><p>반면, Next 13에서는 이를 adjustFallbackFont라는 기능을 통해 기존 Fallback Font의 size-adjust 속성을 조정하기 때문에 Fallback 폰트와 Homemade Apple 폰트 사이의 크기 차이가 발생하지 않고, 이에 따라 Layout Shift가 발생하지 않고 있음을 확인할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/0*pk8S_LzPiteXJC30.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/0*nYvksJpChrkld9k7.gif" /></figure><h3>pre-download google font</h3><p>두 번째로는 google font를 다운로드하는 시점에 대한 것입니다. 기존 next12를 보면 html 파일이 로드된 후, 이 파일이 link 하고 있는 font.googleapis.com에서 폰트를 다운로드하고 있음을 확인할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/0*DDtmBsNFCSMHJPTK.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/0*9c5cps1foEiehIPR.png" /></figure><p>반면, Next 13에서는 build 타임에 미리 google font를 다운로드하여서 로컬 디렉터리에 저장해 두고, html 파일이 이 로컬 파일을 link 하도록 구현되어 있습니다. 이렇게 하면 서로 다른 도메인 간 Connection 연결을 위한 handshaking 과정 없이, 이미 HTML 파일을 다운로드하기 위해 생성했던 Connection을 그대로 사용할 수 있기 때문에 전자보다 비교적 빠른 속도로 파일을 다운로드할 수 있습니다. (물론 Next.js 서버를 운영하는 쪽에서 적절하게 CDN을 사용해서 캐시 정책을 설정해주어야 할 것입니다.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/0*SwjLddlc1MpHJChi.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/0*QPVTnIpS88Zv_G89.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/0*wZ3sZME7Lo0tKGj2.png" /></figure><h3>Webpack Loader</h3><p>지금까지 Next13 이미지가 어떤 특징을 지니는지 Example을 통해 살펴보았습니다. 이제부터는 본격적으로 Source Code를 살펴보면서 위의 기능들을 어떻게 구현했는지에 대해 알아보도록 하겠습니다. 가장 먼저 살펴볼 부분은 webpack-loader입니다. loader는 우리가 아래와 같이 코드를 입력했을 때, 이를 실제 Next가 사용하기 위한 형태로 변환해 주는 역할을 합니다.</p><pre>const homemadeApple = Homemade_Apple({ subsets: [&#39;latin&#39;], weight: [&#39;400&#39;], display: &#39;swap&#39; })</pre><p>next 프로젝트의 webpack-config.ts 파일을 보면 다음과 같이 next에서 사용하는 여러 로더들을 빌드 타임에 사용하고 있음을 알 수 있습니다. 우리에게 익숙한 next-swc-loader, next-image-loader등이 여기에 적혀 있고, 오늘 포스팅의 주제인 next-font-loader도 여기에 들어 있음을 확인할 수 있습니다. 이 loader string은 path.join을 통해 참조되며, 해당 path를 resolve 하면 /packages/next/build/webpack/loaders/next-font-loader를 참조하게 됩니다.</p><pre>// packages/next/build/webpack-config.ts/getBaseWebpackConfig<br>...<br>resolveLoader: {<br>  // The loaders Next.js provides<br>  alias: [<br>    &#39;error-loader&#39;,<br>    &#39;next-swc-loader&#39;,<br>    &#39;next-client-pages-loader&#39;,<br>    &#39;next-image-loader&#39;,<br>    &#39;next-serverless-loader&#39;,<br>    &#39;next-style-loader&#39;,<br>    &#39;next-flight-loader&#39;,<br>    &#39;next-flight-client-entry-loader&#39;,<br>    &#39;noop-loader&#39;,<br>    &#39;next-middleware-loader&#39;,<br>    &#39;next-edge-function-loader&#39;,<br>    &#39;next-edge-ssr-loader&#39;,<br>    &#39;next-middleware-asset-loader&#39;,<br>    &#39;next-middleware-wasm-loader&#39;,<br>    &#39;next-app-loader&#39;,<br>    &#39;next-font-loader&#39;,<br>  ].reduce((alias, loader) =&gt; {<br>    // using multiple aliases to replace `resolveLoader.modules`<br>    alias[loader] = path.join(__dirname, &#39;webpack&#39;, &#39;loaders&#39;, loader)</pre><pre>return alias<br>  }, {} as Record&lt;string, string&gt;),<br>  modules: [<br>    &#39;node_modules&#39;,<br>    ...nodePathList, // Support for NODE_PATH environment variable<br>  ],<br>  plugins: [],<br>},</pre><p>next-font-loader는 다음과 같이 2개의 구성 요소로 구성되어 있습니다. 실제로 webpack loader가 참조하는 index.ts와 이 index.ts파일에서 참조하는 postcss-next-font.ts 입니다. 각각의 파일이 어떻게 구성되어 있는지를 살펴보도록 하겠습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/0*Q6nnPun9_r3d7l68.png" /></figure><h3>nextFontLoader</h3><p>next-font-loader는 크게 2가지 부분으로 구성되어 있습니다. packages/font/src/google/loader.ts의 downloadGoogleFonts 함수를 호출해서 빌드 타임에(애초에 webpack loader가 실행되는 시점은 빌드 타임이기 때문입니다.) googleFont를 다운받고 zero-layout-shift를 위한 size-adjust를 진행하는 부분과 이 결과를 바탕으로 className을 만들고 여기에 font-family, font-weight, font-style css를 적용하는 부분입니다. 실제로 위의 Next13 예제에서 Homemade Apple 폰트를 적용한 main tag에는 다음과 같은 className이 적용되어 있는 것을 확인할 수 있으며, 이 className은 아래와 같은 css가 적용됩니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/0*0xeDO-xJKq1MTI4k.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/0*S_5laWEMDReT_KQg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cgVuNfFuX_4dwbOw.png" /></figure><p>우선 googleFont를 다운로드 받고, fallback font를 처리하는 단계부터 살펴보도록 하겠습니다. nextFontLoader라는 함수에서 fontLoader라는 async 함수를 호출함으로써 이 단계를 수행하게 되는데 fontLoader라는 함수는 googleFont의 경우 pakages/font/google/loader.js를 의미하게 되며, 이는 packages/font/src/google/loader.ts를 빌드한 결과물이 됩니다. 즉, nextFontLoader에서 호출하는 fontLoader라는 함수는 packages/font/src/google/loader.ts의 downloadGoogleFonts라는 함수를 의미하는 것입니다.</p><pre>export default async function nextFontLoader(this: any) {<br>...<br>    try {<br>      const fontLoader: FontLoader = require(path.join(<br>        this.resourcePath,<br>        &#39;../loader.js&#39;<br>      )).default<br>      let { css, fallbackFonts, adjustFontFallback, weight, style, variable } =<br>        await fontLoader({<br>          functionName,<br>          variableName,<br>          data,<br>          config: fontLoaderOptions,<br>          emitFontFile,<br>          resolve: (src: string) =&gt;<br>            promisify(this.resolve)(<br>              path.dirname(<br>                path.join(this.rootContext, relativeFilePathFromRoot)<br>              ),<br>              src.startsWith(&#39;.&#39;) ? src : `./${src}`<br>            ),<br>          isDev,<br>          isServer,<br>          loaderContext: this,<br>        };</pre><h3>downloadGoogleFonts</h3><p>downloadGoogleFonts라는 함수는 230줄에 달하는 굉장히 긴 함수이므로, Semantic 한 부분을 기준으로 나누어서 설명하도록 하겠습니다. 전체 Source Code는 official repository를 참고하시는 것이 좋습니다. 이 글에서는 fallback font의 size-adjust를 수행하는 부분, 폰트를 다운로드 하는 부분, 그리고 결과를 생성하는 부분의 세 군데로 나누어서 설명하도록 하겠습니다.</p><p><a href="https://github.com/vercel/next.js/blob/canary/packages/font/src/google/loader.ts">https://github.com/vercel/next.js/blob/canary/packages/font/src/google/loader.ts</a></p><h4>size-adjust</h4><p>첫 번째로 거치는 단계는 adjustFontFallbackMetrics를 계산하는 부분입니다. google-font-metrics.json이라는 Map을 불러와서 fontFamily를 key로 준 값을 읽어온 후에, 이 값을 calculateSizeAdjustValues에 넣어 size-adjust, line-gap 등의 fallback font를 조정하기 위한 값을 계산하고 있음을 알 수 있습니다. 이 부분은 next/font가 zero-layout-shift를 구현하기 위한 핵심 로직으로, 내가 Homemade Apple 폰트를 사용하기로 했다고 하면, 이 폰트에 대한 fallback font를 결정한 뒤에(serif or sans-serif), Homemade Apple 폰트와 fallback 폰트와의 layout shift를 발생시킬 수 있는 size 차이를 비교해서 size-adjust 속성을 조정하는 방식으로 동작합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/0*fPBMnCN5jCoeM46C.png" /></figure><blockquote><em>The size-adjust CSS descriptor defines a multiplier for glyph outlines and metrics associated with this font. This makes it easier to harmonize the designs of various fonts when rendered at the same font size.</em></blockquote><p><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/size-adjust">size-adjust — CSS: Cascading Style Sheets | MDN</a></p><pre>// Find fallback font metrics<br>let adjustFontFallbackMetrics: AdjustFontFallback | undefined<br>if (adjustFontFallback) {<br>try {<br>  const { ascent, descent, lineGap, fallbackFont, sizeAdjust } =<br>    calculateSizeAdjustValues(<br>      require(&#39;next/dist/server/google-font-metrics.json&#39;)[fontFamily]<br>    )<br>  adjustFontFallbackMetrics = {<br>    fallbackFont,<br>    ascentOverride: `${ascent}%`,<br>    descentOverride: `${descent}%`,<br>    lineGapOverride: `${lineGap}%`,<br>    sizeAdjust: `${sizeAdjust}%`,<br>  }<br>}<br>...<br>}</pre><pre>const result = {<br>    fallbackFonts: fallback,<br>    weight:<br>      weights.length === 1 &amp;&amp; weights[0] !== &#39;variable&#39;<br>        ? weights[0]<br>        : undefined,<br>    style: styles.length === 1 ? styles[0] : undefined,<br>    variable,<br>    adjustFontFallback: adjustFontFallbackMetrics,<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*-GZEY4Ycrds6TClh.jpg" /></figure><p>위에서 호출하는 calculateSizeAdjustValues라는 함수는 다음과 같이 생겼는데, 넘겨준 fontMetrics의 category값이 “serif”이면 Times New Roman을, “sans serif” 이거나 “serif”가 아니면 Arial을 fallback으로 설정합니다.</p><pre>// packages/next/server/font-utils.ts<br>export const DEFAULT_SERIF_FONT = {<br>  name: &#39;Times New Roman&#39;,<br>  xAvgCharWidth: 821,<br>  azAvgWidth: 854.3953488372093,<br>  unitsPerEm: 2048,<br>}<br>export const DEFAULT_SANS_SERIF_FONT = {<br>  name: &#39;Arial&#39;,<br>  xAvgCharWidth: 904,<br>  azAvgWidth: 934.5116279069767,<br>  unitsPerEm: 2048,<br>}</pre><pre>export function calculateSizeAdjustValues(fontMetrics: any) {<br>  let { category, ascent, descent, lineGap, unitsPerEm, azAvgWidth } =<br>    fontMetrics<br>  const fallbackFont =<br>    category === &#39;serif&#39; ? DEFAULT_SERIF_FONT : DEFAULT_SANS_SERIF_FONT<br>  const mainFontAvgWidth = azAvgWidth / unitsPerEm<br>  const fallbackFontAvgWidth = fallbackFont.azAvgWidth / fallbackFont.unitsPerEm<br>  let sizeAdjust = azAvgWidth ? mainFontAvgWidth / fallbackFontAvgWidth : 1<br>  ascent = formatOverrideValue(ascent / (unitsPerEm * sizeAdjust))<br>  descent = formatOverrideValue(descent / (unitsPerEm * sizeAdjust))<br>  lineGap = formatOverrideValue(lineGap / (unitsPerEm * sizeAdjust))<br>  return {<br>    ascent,<br>    descent,<br>    lineGap,<br>    fallbackFont: fallbackFont.name,<br>    sizeAdjust: formatOverrideValue(sizeAdjust),<br>  }<br>}</pre><p>위 함수에 fontMetrics로 넘겨주는 값은 다음과 같이 하드코딩된 JSON map의 형태로 저장되어 있습니다. 즉 next는 size-adjust를 수행하기 위해서 필요한 값들을 자신들이 지정한 fallback font인 Times new Roman과 Arial에 대해 모두 기록해 놓고 빌드 시에 이 값을 불러와서 size-adjust 값을 계산한 뒤 사용하는 것입니다.</p><pre>// packages/next/server/google-font-metrics.json<br>...<br>&quot;Noto Sans Lao&quot;: {<br>    &quot;category&quot;: &quot;sans-serif&quot;,<br>    &quot;ascent&quot;: 1183,<br>    &quot;descent&quot;: -462,<br>    &quot;lineGap&quot;: 0,<br>    &quot;xAvgCharWidth&quot;: 556,<br>    &quot;unitsPerEm&quot;: 1000,<br>    &quot;azAvgWidth&quot;: 485.8139534883721<br>},<br>&quot;Homemade Apple&quot;: {<br>    &quot;category&quot;: &quot;handwriting&quot;,<br>    &quot;ascent&quot;: 1327,<br>    &quot;descent&quot;: -866,<br>    &quot;lineGap&quot;: 18,<br>    &quot;xAvgCharWidth&quot;: 567,<br>    &quot;unitsPerEm&quot;: 1024,<br>    &quot;azAvgWidth&quot;: 573.6976744186046<br>},<br>&quot;Noto Sans Ogham&quot;: {<br>    &quot;category&quot;: &quot;sans-serif&quot;,<br>    &quot;ascent&quot;: 1069,<br>    &quot;descent&quot;: -293,<br>    &quot;lineGap&quot;: 0,<br>    &quot;xAvgCharWidth&quot;: 538,<br>    &quot;unitsPerEm&quot;: 1000,<br>    &quot;azAvgWidth&quot;: 552.5581395348837<br>},<br>...</pre><h4>download fonts</h4><p>Homemade Apple 폰트에 대한 fallback 폰트를 정하고, 이 폰트에 대해 zero-layout-shift를 구현하기 위한 size-adjust 과정이 마무리된 뒤에는 실제로 Homemade Apple 폰트를 빌드 타임에 다운로드 받아서 .next/static/media 하위에 저장해야 합니다. 폰트를 다운로드하기 위해서는 우선 @font-face로 구성된 css 파일을 먼저 다운로드한 뒤, 이 파일에 명시된 font들을 다운로드해야 합니다.</p><p>이를 위해 먼저 Map 객체로 구성된 cssCache map에 해당 폰트에 대한 cache가 있는지를 먼저 확인합니다. cache가 없는 경우 fetch api를 사용해서 직접 해당 폰트에 대한 css(@font-face로 구성된)를 다운받아 옵니다.</p><pre>const hasCachedCSS = cssCache.has(url)<br>let fontFaceDeclarations = hasCachedCSS<br>  ? cssCache.get(url)<br>  : await fetchCSSFromGoogleFonts(url, fontFamily).catch(() =&gt; null)<br>if (!hasCachedCSS) {<br>  cssCache.set(url, fontFaceDeclarations)<br>} else {<br>  cssCache.delete(url)<br>}<br>if (fontFaceDeclarations === null) {<br>  nextFontError(`Failed to fetch \`${fontFamily}\` from Google Fonts.`)<br>}</pre><pre>// packages/font/src/google/utils.ts<br>export async function fetchCSSFromGoogleFonts(url: string, fontFamily: string) {<br>    let cssResponse<br>    const res = await fetch(url, {<br>      headers: {<br>        // The file format is based off of the user agent, make sure woff2 files are fetched<br>        &#39;user-agent&#39;:<br>          &#39;Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36&#39;,<br>      },<br>    })<br>    cssResponse = await res.text()<br>    return cssResponse<br>}</pre><p>다음으로는 받아온 @font-facae css 파일을 바탕으로 실제 폰트 파일(대개 woff2 format)을 다운받아 옵니다. 이 폰트 파일 또한 @font-face css파일과 마찬가지로 cache에 값이 있는지를 확인하는 단계를 거칩니다.</p><p>폰트 파일을 받아온 이후에는 이 파일을 로컬 디렉토리인 .next/static/media 하위에 저장하고, fontFaceDeclarations(@font-face css파일)에 google도메인을 바라보고 있는 스트링 값들을 전부 방금 폰트 파일을 저장한 로컬 디렉터리를 바라보도록 수정해 줍니다.</p><pre>// CSS Variables may be set on a body tag, ignore them to keep the CSS module pure<br>fontFaceDeclarations = fontFaceDeclarations.split(&#39;body {&#39;)[0]</pre><pre>// Find font files to download<br>const fontFiles: Array&lt;{<br>  googleFontFileUrl: string<br>  preloadFontFile: boolean<br>}&gt; = []<br>let currentSubset = &#39;&#39;<br>for (const line of fontFaceDeclarations.split(&#39;\n&#39;)) {<br>  // Each @font-face has the subset above it in a comment<br>  const newSubset = /\/\* (.+?) \*\//.exec(line)?.[1]<br>  if (newSubset) {<br>    currentSubset = newSubset<br>  } else {<br>    const googleFontFileUrl = /src: url\((.+?)\)/.exec(line)?.[1]<br>    if (<br>      googleFontFileUrl &amp;&amp;<br>      !fontFiles.some(<br>        (foundFile) =&gt; foundFile.googleFontFileUrl === googleFontFileUrl<br>      )<br>    ) {<br>      fontFiles.push({<br>        googleFontFileUrl,<br>        preloadFontFile:<br>          !!preload &amp;&amp; (callSubsets ?? subsets).includes(currentSubset),<br>      })<br>    }<br>  }<br>}<br>// Download font files<br>const downloadedFiles = await Promise.all(<br>  fontFiles.map(async ({ googleFontFileUrl, preloadFontFile }) =&gt; {<br>    const hasCachedFont = fontCache.has(googleFontFileUrl)<br>    const fontFileBuffer = hasCachedFont<br>      ? fontCache.get(googleFontFileUrl)<br>      : await fetchFontFile(googleFontFileUrl).catch(() =&gt; null)<br>    if (!hasCachedFont) {<br>      fontCache.set(googleFontFileUrl, fontFileBuffer)<br>    } else {<br>      fontCache.delete(googleFontFileUrl)<br>    }<br>    if (fontFileBuffer === null) {<br>      nextFontError(`Failed to fetch \`${fontFamily}\` from Google Fonts.`)<br>    }<br>    const ext = /\.(woff|woff2|eot|ttf|otf)$/.exec(googleFontFileUrl)![1]<br>    // Emit font file to .next/static/media<br>    const selfHostedFileUrl = emitFontFile(<br>      fontFileBuffer,<br>      ext,<br>      preloadFontFile<br>    )<br>    return {<br>      googleFontFileUrl,<br>      selfHostedFileUrl,<br>    }<br>  })<br>)<br>// Replace @font-face sources with self-hosted files<br>let updatedCssResponse = fontFaceDeclarations<br>for (const { googleFontFileUrl, selfHostedFileUrl } of downloadedFiles) {<br>  updatedCssResponse = updatedCssResponse.replace(<br>    new RegExp(escapeStringRegexp(googleFontFileUrl), &#39;g&#39;),<br>    selfHostedFileUrl<br>  )<br>}<br>return {<br>  ...result,<br>  css: updatedCssResponse,<br>}</pre><h4>wrap-up</h4><p>지금까지 downloadGoogleFonts 함수가 하는 역할에 대해 살펴보았습니다. 정리하면 다음과 같습니다. (아래의 모든 과정은 빌드 타임에 일어난다는 사실을 기억해 주세요)</p><ul><li>사용자가 입력한 폰트를 key로 해서 하드코딩된 google-font-metrics.json파일의 JSON Map으로부터 Value를 읽어옴.</li><li>이 Value에는 해당 폰트의 카테고리(Serif, Sans Serif..), size-adjust 계산을 위한 여러 metric들이 들어 있음. 이 값들을 사용해서 사용자가 입력한 폰트와 fallback font의 사이즈를 조정해서 zero-layout-shift가 발생하지 않도록 맞춰줌.</li><li>다음으로는 실제로 폰트를 다운로드하는 단계. 먼저 @font-face가 정의된 css파일을 먼저 다운로드하고, 이 파일 안에 들어있는 실제 폰트 파일들 (woff2, woff)을 다운로드함. (이때 캐시가 있으면 캐시를 사용함.) 실제 폰트 파일을 로컬 파일 시스템에 저장한 뒤에 @font-face가 정의된 파일이 이 로컬 파일 시스템의 디렉터리를 가리키도록 String Replace를 수행함.</li><li>이 값을 리턴함.</li></ul><p>이제 다음은 postcss-next-font를 간단하게 살펴봄으로써, 위에서 다운로드한 폰트와 css파일을 어떻게 className과 css에 바인딩하는지를 살펴보도록 하겠습니다.</p><h3>postcss-next-font</h3><p>postcssNextFontPlugin함수가 하는 일은 결국 아래의 css파일을 생성하는 것입니다. 위의 Next13 예제에서 생성된. next/static/css 디렉터리 안에 들어있는 파일을 의미하며 이 파일은 아래와 같이 HTML의 head에 link의 형태로 들어가게 됩니다. 즉, HTML 파일에 link로 들어가 있는 @font-face css파일은 postcssNextFontPlugin에 의해서 생성된 것이며, 생성된 css 파일은 로컬 파일 시스템에 다운로드된 googleFont를 가리키고, 이 css 파일 안에는 미리 계산된 size-adjust와 같은 값들이 들어 있어서 zero-layout-shift를 가능하게 만드는 것입니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mJQo_oYbOrmaqmVv.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i6aoxuaPIYOcR8So.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/0*vRHIc8RWM0dd4nId.png" /></figure><p>postcss-next-font안에 있는 postcssNextFontPlugin 함수는 downloadGoogleFonts의 결과로부터 실행됩니다. 함수를 실행하기 전에 nextFontLoader에서 fontFamilyHash 값을 생성하는데, 이 값이 위의 예시에서 보았던 className의 hash값이 됩니다.</p><pre>// nextFontLoader<br>const fontFamilyHash = loaderUtils.getHashDigest(<br>    Buffer.from(css),<br>    &#39;md5&#39;,<br>    &#39;hex&#39;,<br>    6<br>)<br>// Add CSS classes, exports and make the font-family localy scoped by turning it unguessable<br>const result = await postcss(<br>    postcssNextFontPlugin({<br>      exports,<br>      fontFamilyHash,<br>      fallbackFonts,<br>      weight,<br>      style,<br>      adjustFontFallback,<br>      variable,<br>    })<br>).process(css, {<br>    from: undefined,<br>})</pre><p>postcssNextFontPlugin은 fontFamilyHash와 fontFamily Name으로부터 가공된 이름을 생성합니다. (아래 그림에서 __Homemade_Apple_bd05f8), 이 값은 css font-family 값으로 들어가게 됩니다. 이렇게 formatFamily를 거쳐 사용될 이름의 hash 값을 생성한 뒤에는, 이전 downloadGoogleFonts에서 처리한 size-adjust와 같은 값들을 css에 반영하는 단계를 거치게 되고, font-family, font-weight, font-style 값까지 모두 css 파일에 반영한 뒤에 리턴하게 됩니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/0*i-lS7Ub35n07fpo-.png" /></figure><pre>const formatFamily = (family: string) =&gt; {<br>    // Turn the font family unguessable to make it localy scoped<br>    return `&#39;__${family.replace(/ /g, &#39;_&#39;)}_${fontFamilyHash}&#39;`<br>  }<br>  <br>  let adjustFontFallbackFamily: string | undefined<br>  if (adjustFontFallback) {<br>    adjustFontFallbackFamily = formatFamily(`${fontFamily} Fallback`)<br>    const fallbackFontFace = postcss.atRule({ name: &#39;font-face&#39; })<br>    const {<br>      fallbackFont,<br>      ascentOverride,<br>      descentOverride,<br>      lineGapOverride,<br>      sizeAdjust,<br>    } = adjustFontFallback<br>    fallbackFontFace.nodes = [<br>      new postcss.Declaration({<br>        prop: &#39;font-family&#39;,<br>        value: adjustFontFallbackFamily,<br>      }),<br>      new postcss.Declaration({<br>        prop: &#39;src&#39;,<br>        value: `local(&quot;${fallbackFont}&quot;)`,<br>      }),<br>      ...(ascentOverride<br>        ? [<br>            new postcss.Declaration({<br>              prop: &#39;ascent-override&#39;,<br>              value: ascentOverride,<br>            }),<br>          ]<br>        : []),<br>      ...(descentOverride<br>        ? [<br>            new postcss.Declaration({<br>              prop: &#39;descent-override&#39;,<br>              value: descentOverride,<br>            }),<br>          ]<br>        : []),<br>      ...(lineGapOverride<br>        ? [<br>            new postcss.Declaration({<br>              prop: &#39;line-gap-override&#39;,<br>              value: lineGapOverride,<br>            }),<br>          ]<br>        : []),<br>      ...(sizeAdjust<br>        ? [<br>            new postcss.Declaration({<br>              prop: &#39;size-adjust&#39;,<br>              value: sizeAdjust,<br>            }),<br>          ]<br>        : []),<br>    ]<br>    root.nodes.push(fallbackFontFace)<br>  }<br>  <br>  const formattedFontFamilies = [<br>    formatFamily(fontFamily),<br>    ...(adjustFontFallbackFamily ? [adjustFontFallbackFamily] : []),<br>    ...fallbackFonts,<br>  ].join(&#39;, &#39;)</pre><pre>// Add class with family, weight and style<br>  const classRule = new postcss.Rule({ selector: &#39;.className&#39; })<br>  classRule.nodes = [<br>    new postcss.Declaration({<br>      prop: &#39;font-family&#39;,<br>      value: formattedFontFamilies,<br>    }),<br>    ...(weight &amp;&amp; !isRange(weight)<br>      ? [<br>          new postcss.Declaration({<br>            prop: &#39;font-weight&#39;,<br>            value: weight,<br>          }),<br>        ]<br>      : []),<br>    ...(style &amp;&amp; !isRange(style)<br>      ? [<br>          new postcss.Declaration({<br>            prop: &#39;font-style&#39;,<br>            value: style,<br>          }),<br>        ]<br>      : []),<br>  ]<br>  root.nodes.push(classRule)</pre><h3>Conclusion</h3><p>지금까지 @next/font가 어떻게 구현되었는지를 살펴봄으로써, 어떻게 next가 font optimization을 내부적으로 수행하는지 살펴보았습니다. 핵심 아이디어를 정리하면 다음과 같습니다.</p><ul><li>font optimization은 빌드 타임에 webpack custom loader를 통해 수행한다.</li><li>zero-layout-shift를 구현하기 위해 next는 Serif / Not Serif의 2가지 Default Fallback Font를 지정하고 있고(Times New Roman, Arial) 이 두 폰트에 대한 다른 모든 구글 폰트의 size-adjust 계산을 위한 값들이 하드코딩되어 있는 font-metrics map을 내부적으로 가지고 있다.</li><li>이 map을 사용해서 fallback 폰트와 사용자가 사용하려는 폰트 사이의 size-adjust를 수행해서 zero-layout-shift를 구현하고, 빌드 타임에 구글 폰트를 다운로드하여 로컬 디렉터리(. next/static/media)에 저장한다.</li><li>이제 @font-face가 포함된 css 파일을 생성해야 하는데, 이는 postcssNextFontPlugin에서 수행하며, fontFamily의 hash 값과 이전 단계에서 계산한 adjustFallbackFont의 여러 값을 css파일에 매핑한다.</li><li>이 css파일은 HTML의 head tag안에 존재하며, @font-face를 가리키는 css파일과, css파일이 가리키는 font 파일이 모두 local directory에 있기 때문에 Same-origin이며, 기존에 연결되어 있던 connection을 그대로 사용할 수 있다.</li></ul><h3>Reference</h3><p><a href="https://nextjs.org/docs/api-reference/next/font">https://nextjs.org/docs/api-reference/next/font</a></p><p><a href="https://nextjs.org/docs/basic-features/font-optimization">https://nextjs.org/docs/basic-features/font-optimization</a></p><p><a href="https://www.lydiahallie.io/blog/optimizing-webfonts-in-nextjs-13">https://www.lydiahallie.io/blog/optimizing-webfonts-in-nextjs-13</a></p><p><a href="https://web.dev/cls/">https://web.dev/cls/</a></p><p><a href="https://fonts.google.com/knowledge/glossary/fout">FOUT - Fonts Knowledge - Google Fonts</a></p><ul><li>🌏글로벌 Top 교육 앱 QANDA(콴다)를 함께 만들어 갈 Frontend개발자들을 기다리고 있습니다!</li><li>🖥️콴다 팀의 개발 문화가 궁금하다면? ➡️ <a href="https://www.youtube.com/watch?v=9Xtm92NAU58">Inside QANDA: 최고의 글로벌 교육 서비스를 개발한다는 것</a></li><li>🕹️콴다 Frontend Team은 채용 중 입니다!➡️ <a href="http://bit.ly/3pVjlmR">공고 확인하기</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bb72c2bae39" width="1" height="1" alt=""><hr><p><a href="https://blog.mathpresso.com/how-next-font-works-8bb72c2bae39">How @next/font works</a> was originally published in <a href="https://blog.mathpresso.com/">Team QANDA</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Concept of React Scheduler]]></title>
            <link>https://sckimynwa.medium.com/concept-of-react-scheduler-2c887cbfe5a8?source=rss-9ce465f93d9e------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c887cbfe5a8</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[scheduler]]></category>
            <category><![CDATA[fiber]]></category>
            <dc:creator><![CDATA[Yeoul]]></dc:creator>
            <pubDate>Sat, 14 Jan 2023 12:16:08 GMT</pubDate>
            <atom:updated>2023-01-14T12:16:08.588Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rbxfcNzm15mIxkbb.png" /></figure><h3>Overview</h3><p><a href="https://medium.com/@yeoulcoding/react-mount-system-deep-dive-sync-mode-c89c1ace14af">이전 포스팅</a>에서 React Sync Mode(Concurrent Mode가 아닌 것, Legacy Mode)가 어떻게 동작하는지에 대해 Source Code Level에서 간략하게 살펴보았습니다. 이번 포스팅부터는 해당 내용을 기반으로 해서 Concurrent Mode가 어떻게 동작하는지에 대해서 한 단계씩 살펴보려고 합니다. Fiber, workInProgress Node, workLoopSync와 같은 용어들을 이해하고 있다는 전제로 전개되므로 이전 포스팅을 먼저 읽어보시는 것을 추천합니다.</p><p><strong><em>Concurrent Mode의 핵심은 Task를 수행하는 도중에 더 높은 우선순위를 지니고 있는 Task가 들어오면, 지금 처리 중인 Task를 “일시중단(Pause)”하고, 우선순위가 더 높은 Task를 먼저 처리한 후에, 다시 중단된 Task를 “재개(Resume)”하는 것</em></strong>입니다. React는 이것을 “Lane Model”이라는 개념과 “Scheduler”를 통해 해결합니다. 두 내용을 한 번에 다루기에는 분량이 많기 때문에, 이번 포스팅에서는 “Scheduler”에 대한 내용을 다루고, 다음 포스팅에서 Lane Model과 Event Priority에 대해 다루도록 하겠습니다.</p><h3>Basic Idea</h3><p>이전 포스팅에서 살펴보았던 Sync Mode에서는 renderRootSync에서 호출하는 workLoopSync가 root로 부터 모든 Fiber를 순회하면서 performUnitOfWork를 수행하고, 그 뒤에 commitPhase를 거쳐 화면에 반영됩니다. 화면을 다시 렌더해야 할 때, 모든 Fiber를 순회하면서 performUnitOfWork를 모두 처리하기 전까지는 commitPhase로 넘어가지 않기 때문에 이 workLoopSync를 처리하는 시간이 길어질 경우에는 아래와 같이 사용자에게 Delay를 주어 Application이 느리다는 인상을 주게 됩니다.</p><pre>// The work loop is an extremely hot path. Tell Closure not to inline it.<br>/** @noinline */<br>function workLoopSync() {<br>  // Perform work without checking if we need to yield between fiber.<br>  while (workInProgress !== null) {<br>    performUnitOfWork(workInProgress);<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/0*82kk4Q13byw9Rqb1.gif" /></figure><p>반면, Concurrent Mode에서는 renderRootConcurrent에서 workLoopConcurrent를 호출하는데, <strong><em>이 함수에서는 “shouldYield”라는 함수를 매 performUnitOfWork를 실행하기 전에 체크함으로써, Frame interval보다 Task를 처리하는 시간이 길어지거나, 우선순위가 더 높은 Task가 들어올 경우, 언제든지 현재의 workLoopConcurrent를 중단하고, Frame을 업데이트하거나, 더 우선순위가 높은 Task를 처리할 수 있도록 양보(yield) 합니다.</em></strong> (Concurrent Mode라고 renderRootConcurrent만 호출하는 것은 아닙니다. 우선순위가 높은 Task의 경우 renderRootSync를 호출하기도 하지만, 해당 내용은 Concurrent의 개념적인 내용보다는 Detail에 해당하므로 이번 포스팅에서 다루지 않겠습니다.)</p><p>아래의 그림과 같이 한번의 사용자 input 변화는 처리하는데 시간이 오래 걸리는 Cell 변화를 수반합니다. 하지만 Application의 입장에서 는 해당 Cell을 렌더 하는 것보다 사용자 input update에 빠르게 반응하는 것이 더 중요하기 때문에 Cell을 렌더 하는 작업을 수행하다가 더 높은 Task(사용자 input update로 인한 변경사항)가 들어오면 기존 작업을 잠시 중단하고 사용자 input update에 반응하는 task를 더 먼저 수행한 뒤, Cell을 렌더 하게 됩니다. (부연 설명을 추가하자면, 아래의 예시에서 모든 Cell의 변경사항을 DOM에 반영하는 것은 아닙니다. transition API를 잘 사용하면 중간 상태를 건너뛰고, 최종 상태만 렌더하기도 하는데, 이 내용은 이번 Scheduler의 범위를 벗어나므로 이번 포스팅에서는 다루지 않겠습니다.)</p><pre>/** @noinline */<br>function workLoopConcurrent() {<br>  // Perform work until Scheduler asks us to yield<br>  while (workInProgress !== null &amp;&amp; !shouldYield()) {<br>    // $FlowFixMe[incompatible-call] found when upgrading Flow<br>    performUnitOfWork(workInProgress);<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/0*ZT1qOO6pNKpTPeX3.gif" /></figure><p>즉, Concurrent Mode는 사용자에게 더 중요한 Task를 먼저 수행하도록 양보함으로써 사용자 경험을 높이는 방법에 대한 것입니다.</p><h3>Backgrounds</h3><p>본격적으로 Scheduler로 들어가기 전에 이해해야 할 배경지식이 있습니다. React Scheduler는 Task 스케줄링을 위해 Host 환경(Browser, Node.js)의 Task Scheduling을 사용합니다. <em>따라서 Event Loop과 setImmediate, MessageQueue와 setTimeout에 대한 이해가 필요합니다</em>. 두 번째로, task의 우선순위를 관리하기 위해 React는 minHeap 기반의 Priority Queue를 사용하기 때문에 <em>Priority Queue와 MinHeap에 대한 이해가 필요</em>합니다. 이 포스팅에서는 이 개념들에 대해 간단히 짚고 넘어가는 정도로만 설명할 예정이며, 자세한 내용은 아래 Reference Section을 참고해주세요.</p><h3>Event Loop, setImmediate</h3><p>Browser, Node.js와 같은 Host 환경에서 렌더링을 block 하지 않고 task를 스케줄 하기 위해서는 해당 task를 macroTask로 등록하여 mainStack이 비워진 후에 EventLoop를 거쳐 실행하도록 해야 합니다. 이를 위해 setTimeout을 사용할 수 있으나, 해당 API는 역사적인 이슈로 인해 4ms clamping 이슈가 있고, 이를 개선하기 위해 React에서는 setImmediate와 MessageChannel을 사용합니다. (물론 둘 다 지원하지 않는 환경에서는 setTimout을 쓰긴 합니다.</p><p>즉, userEvent 등의 업데이트로 인해 화면의 rerender가 필요할 때, performConcurrentWorkOnRoot를 task로 등록하여 실행하는데, 이때, 이 함수를 바로 실행하는 것이 아니라, scheduleCallback이라는 스케줄러 함수를 통해 실행하고, 이 함수는 넘어온 performConcurrentWorkOnRoot를 macroTask로 등록하여 main call stack이 비워지면, EventLoop를 거쳐 실행되게 되는 것입니다. 여기까지의 내용을 간략하게 도표로 그려보면 다음과 같습니다. (실제로 performConcurrentWorkOnRoot가 바로 macroTask에 등록되는 것은 아니지만 개념상 지금은 제어권의 관점에서 이렇게 이해한 뒤에, 글을 진행해 가면서 구체적으로 살펴보도록 하겠습니다.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/0*qqKi11hiq9FuM5lC.png" /></figure><pre>// packages/scheduler/src/forks/Scheduler.js</pre><pre>let schedulePerformWorkUntilDeadline;<br>if (typeof localSetImmediate === &#39;function&#39;) {<br>  // Node.js and old IE.<br>  // There&#39;s a few reasons for why we prefer setImmediate.<br>  //<br>  // Unlike MessageChannel, it doesn&#39;t prevent a Node.js process from exiting.<br>  // (Even though this is a DOM fork of the Scheduler, you could get here<br>  // with a mix of Node.js 15+, which has a MessageChannel, and jsdom.)<br>  // <a href="https://github.com/facebook/react/issues/20756">https://github.com/facebook/react/issues/20756</a><br>  //<br>  // But also, it runs earlier which is the semantic we want.<br>  // If other browsers ever implement it, it&#39;s better to use it.<br>  // Although both of these would be inferior to native scheduling.<br>  schedulePerformWorkUntilDeadline = () =&gt; {<br>    localSetImmediate(performWorkUntilDeadline);<br>  };<br>} else if (typeof MessageChannel !== &#39;undefined&#39;) {<br>  // DOM and Worker environments.<br>  // We prefer MessageChannel because of the 4ms setTimeout clamping.<br>  const channel = new MessageChannel();<br>  const port = channel.port2;<br>  channel.port1.onmessage = performWorkUntilDeadline;<br>  schedulePerformWorkUntilDeadline = () =&gt; {<br>    port.postMessage(null);<br>  };<br>} else {<br>  // We should only fallback here in non-browser environments.<br>  schedulePerformWorkUntilDeadline = () =&gt; {<br>    // $FlowFixMe[not-a-function] nullable value<br>    localSetTimeout(performWorkUntilDeadline, 0);<br>  };<br>}</pre><h3>Min Heap, Priority Queue</h3><p>앞서 간단히 언급한 것처럼, React는 각 Task에 우선순위를 붙여 Priority Queue에 저장한 후, 우선순위에 따라 정렬된 task를 peek 해서 사용합니다. 따라서 하나의 task를 수행하다가 shouldYield가 호출되어 해당 task가 중단된 후, 다시 재개할 때가 되어 priority Queue를 peek 했을 때, 그 사이에 queue에 다른 task가 push 되고, 이 task가 기존에 작업하던 task보다 우선순위가 높다면, 새롭게 push 된 task가 나오게 되며, 따라서 React는 이 작업을 먼저 수행하게 되는 것입니다.</p><p>자세한 내용을 ensureRootIsScheduled에서 호출하는 scheduleCallback의 SourceCode를 살펴봄으로써 확인해 보겠습니다. 아래 코드에서 확인할 수 있는 것처럼, reconciler에서 호출하는 scheduleCallback은 Scheduler 패키지의 scheduleCallback에 priorityLevel과 callback(여기서의 callback은 performConcurrentWorkOnRoot가 됩니다.)을 넘기고 종료됩니다.</p><pre>// packages/react-reconciler/src/ReactFiberWorkLoop.js<br>function scheduleCallback(priorityLevel, callback) {<br>  if (__DEV__) {<br>    // If we&#39;re currently inside an `act` scope, bypass Scheduler and push to<br>    // the `act` queue instead.<br>    const actQueue = ReactCurrentActQueue.current;<br>    if (actQueue !== null) {<br>      actQueue.push(callback);<br>      return fakeActCallbackNode;<br>    } else {<br>      return Scheduler_scheduleCallback(priorityLevel, callback);<br>    }<br>  } else {<br>    // In production, always call Scheduler. This function will be stripped out.<br>    return Scheduler_scheduleCallback(priorityLevel, callback);<br>  }<br>}</pre><p>이 부분부터는 reconciler에서 Scheduler로 제어권이 넘어오게 되는데 Scheduler의 scheduleCallback은 queue에 넣을 task를 생성하는 부분과, 해당 Task를 Queue에 넣고 해당 Task를 실행하는 Callback Function을 Event Loop에 던지는 부분입니다. task에 들어가는 callback은 위에서 소개한 도식의 흐름에서 “performWorkOnConcurrentRoot”에 해당합니다.</p><p>여기서 중요한 부분은 expirationTime인데, 해당 Task를 PriorityQueue에서 정렬할 때 사용하는 기준인 sortIndex가 이후 코드에서 이 expirationTime으로 설정되며, 이는 해당 task가 queue에 push 된 시간인 startTime에 해당 task의 Priority Level에 따른 Timout이 더해져서 정해집니다. <strong><em>즉, Task가 빨리 push 되었을수록, 그리고 Task의 우선순위가 높을수록 Scheduler에 의해 먼저 처리된다는 것입니다.</em></strong></p><pre>// unstable_scheduleCallback<br>var currentTime = getCurrentTime();</pre><pre>var startTime;<br>if (typeof options === &#39;object&#39; &amp;&amp; options !== null) {<br>var delay = options.delay;<br>if (typeof delay === &#39;number&#39; &amp;&amp; delay &gt; 0) {<br>  startTime = currentTime + delay;<br>} else {<br>  startTime = currentTime;<br>}<br>} else {<br>  startTime = currentTime;<br>}</pre><pre>var timeout;<br>switch (priorityLevel) {<br>case ImmediatePriority:<br>  timeout = IMMEDIATE_PRIORITY_TIMEOUT;<br>  break;<br>case UserBlockingPriority:<br>  timeout = USER_BLOCKING_PRIORITY_TIMEOUT;<br>  break;<br>case IdlePriority:<br>  timeout = IDLE_PRIORITY_TIMEOUT;<br>  break;<br>case LowPriority:<br>  timeout = LOW_PRIORITY_TIMEOUT;<br>  break;<br>case NormalPriority:<br>default:<br>  timeout = NORMAL_PRIORITY_TIMEOUT;<br>  break;<br>}</pre><pre>var expirationTime = startTime + timeout;</pre><pre>var newTask: Task = {<br>    id: taskIdCounter++,<br>    callback,<br>    priorityLevel,<br>    startTime,<br>    expirationTime,<br>    sortIndex: -1,<br>};</pre><p>위에서 언급한 것처럼 task의 sortIndex가 expirationTime으로 설정되며, 이 task가 taskQueue에 push 된 이후에 requestHostCallback함수를 통해 flushWork라는 함수를 EventLoop에 macroTask로 schedule 합니다.</p><pre>// unstable_scheduleCallback<br>newTask.sortIndex = expirationTime;<br>push(taskQueue, newTask);<br>if (enableProfiling) {<br>  markTaskStart(newTask, currentTime);<br>  newTask.isQueued = true;<br>}<br>// Schedule a host callback, if needed. If we&#39;re already performing work,<br>// wait until the next time we yield.<br>if (!isHostCallbackScheduled &amp;&amp; !isPerformingWork) {<br>  isHostCallbackScheduled = true;<br>  requestHostCallback(flushWork);<br>}</pre><p>requestHostCallback함수에서는 flushWork라는 callback을 받아서 scheduledHostCallback으로 설정하고 schedulePerformWorkUntilDeadline이라는 위에서 살펴보았던 setImmediate, setTimeout, MessageQueue를 사용한 Scheduling Wrapper 함수를 실행함으로써 EventLoop의 macroTask로 해당 callback(flushWork)를 넘깁니다.</p><p>주의할 점은 여기서 2가지 종류의 callback이 나오는데 이 두 개를 같은 callback으로 혼동하기 쉽다는 것입니다. taskQueue에 들어가는 task의 callback인 performConcurrentWorkOnRoot와 schedulePerformWorkUntilDeadline에 의해 EventLoop로 들어가는 callback인 flushWork입니다. EventLoop에 의해 실행되는 callback은 flushWork이며, 이 함수가 workLoop를 호출하고, 여기서 taskQueue를 peek 해서 task의 callback을 실행하는데, 이때의 callback이 performConcurrentWorkOnRoot인 것입니다. 이 흐름은 이후 도식을 통해 다시 한번 살펴보도록 하겠습니다.</p><pre>function requestHostCallback(callback) {<br>  scheduledHostCallback = callback;<br>  if (!isMessageLoopRunning) {<br>    isMessageLoopRunning = true;<br>    schedulePerformWorkUntilDeadline();<br>  }<br>}</pre><pre>if (typeof localSetImmediate === &#39;function&#39;) {<br>	...<br>  schedulePerformWorkUntilDeadline = () =&gt; {<br>    localSetImmediate(performWorkUntilDeadline);<br>  };<br>} </pre><pre>const performWorkUntilDeadline = () =&gt; {<br>  if (scheduledHostCallback !== null) {<br>    let hasMoreWork = true;<br>    try {<br>      // $FlowFixMe[not-a-function] found when upgrading Flow<br>      hasMoreWork = scheduledHostCallback(hasTimeRemaining, currentTime);<br>    } <br>    ...<br>  }<br>...<br>};</pre><p>React에서 사용하는 MinHeap은 Scheduler package에 들어있으며, 다음과 같이 구현되어 있습니다.</p><pre>// packages/scheduler/src/SchedulerMinHeap.js</pre><pre>type Heap&lt;T: Node&gt; = Array&lt;T&gt;;<br>type Node = {<br>  id: number,<br>  sortIndex: number,<br>  ...<br>};</pre><pre>export function push&lt;T: Node&gt;(heap: Heap&lt;T&gt;, node: T): void {<br>...<br>}</pre><pre>export function peek&lt;T: Node&gt;(heap: Heap&lt;T&gt;): T | null {<br>...<br>}</pre><pre>export function pop&lt;T: Node&gt;(heap: Heap&lt;T&gt;): T | null {<br>...<br>}</pre><pre>function siftUp&lt;T: Node&gt;(heap: Heap&lt;T&gt;, node: T, i: number): void {<br>...<br>}</pre><pre>function siftDown&lt;T: Node&gt;(heap: Heap&lt;T&gt;, node: T, i: number): void {<br>...<br>}</pre><pre>function compare(a: Node, b: Node) {<br>...<br>}</pre><h3>Scheduling Processs</h3><p>지금까지의 과정을 살펴보면 Scheulder와 Reconciler가 제어를 주거니 받거니 하면서 다음과 같이 협력하는 것을 확인할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*d7jHJaB8dU7HepyH.png" /></figure><p>Reconciler에서 update 해야 하는 이벤트를 하나 받으면 performConcurrentWorkOnRoot라는 함수를 scheduleCallback이라는 함수를 통해 Scheduler로 넘기게 됩니다. Scheduler는 이 scheduleCallback이라는 함수를 실행하면서 performConcurrentWorkOnRoot를 callback으로 하는 task를 만들고 이를 taskQueue에 밀어 넣습니다. 그리고 requestHostCallback에 flushWork라는 함수를 macroTask로 밀어 넣으면서 이 flushWork라는 함수가 EventLoop에 의해 스케줄 되어 호출될 수 있도록 합니다.</p><h3>flushwork &amp; workLoop</h3><p>그렇다면 flushWork는 어떤 역할을 하는 함수일까요? 실제 구현을 살펴보면 다음과 같습니다. 굉장히 간단하게 되어 있는데, 그냥 workLoop라는 함수를 실행하고 종료하는 것으로 함수가 구성되어 있습니다.</p><pre>try {<br>  // No catch in prod code path.<br>  return workLoop(hasTimeRemaining, initialTime);<br>} finally {<br>  //<br>}</pre><p>flushWork에서 실행되는 workLoop라는 함수는 Scheduler의 핵심 모듈(Core Module)이라고 할 수 있습니다. 이 함수는 먼저 자기 자신이 실행될 수 있을 정도로 잔여시간이 남아 있는지를 확인한 후에, 남아있다면, taskQueue에서 우선순위가 가장 높은 task를 꺼내 이 task의 callback을 실행합니다. 바로 이 코드를 통해 performConcurrentWorkOnRoot가 비로소 실행되게 되는 것이며, 제어권이 reconciler로 넘어와 이 함수 안에서 root로부터 fiber tree를 순회하며 재조정과정을 거치는 것입니다.</p><pre>let currentTime = initialTime;<br>  advanceTimers(currentTime);<br>  currentTask = peek(taskQueue);<br>  while (<br>    currentTask !== null &amp;&amp;<br>    !(enableSchedulerDebugging &amp;&amp; isSchedulerPaused)<br>  ) {<br>    if (<br>      currentTask.expirationTime &gt; currentTime &amp;&amp;<br>      (!hasTimeRemaining || shouldYieldToHost())<br>    ) {<br>      // This currentTask hasn&#39;t expired, and we&#39;ve reached the deadline.<br>      break;<br>    }<br>    const callback = currentTask.callback;<br>    if (typeof callback === &#39;function&#39;) {<br>      currentTask.callback = null;<br>      currentPriorityLevel = currentTask.priorityLevel;<br>      const didUserCallbackTimeout = currentTask.expirationTime &lt;= currentTime;<br>      const continuationCallback = callback(didUserCallbackTimeout);<br>      currentTime = getCurrentTime();<br>      if (typeof continuationCallback === &#39;function&#39;) {<br>        currentTask.callback = continuationCallback;<br>        advanceTimers(currentTime);<br>        return true;<br>      } else {<br>        if (currentTask === peek(taskQueue)) {<br>          pop(taskQueue);<br>        }<br>        advanceTimers(currentTime);<br>      }<br>    } else {<br>      pop(taskQueue);<br>    }<br>    currentTask = peek(taskQueue);<br>  }</pre><pre>// Return whether there&#39;s additional work<br>  if (currentTask !== null) {<br>    return true;<br>  } else {<br>    const firstTimer = peek(timerQueue);<br>    if (firstTimer !== null) {<br>      requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);<br>    }<br>    return false;<br>  }</pre><h3>Suspend and Resume Task</h3><p>지금까지 이벤트가 발생했을 때, 어떤 과정을 통해 task가 스케줄 되며, 실행되는지에 대해 알아보았습니다. 이제 마지막으로 task를 실행하다가 더 높은 우선순위를 가진 task가 들어왔을 때, 기존에 실행하는 task를 어떻게 suspend 하고 이후 다시 resume 하는지에 대해 살펴보도록 하겠습니다. 코드의 구현은 reconciler의 performConcurrentWorkOnRoot와 Scheduler의 workLoop에 들어있습니다.</p><p>우선은 performConcurrentWorkOnRoot에 대한 부분입니다. 주목해야 하는 부분은 return 하는 부분인데, root.callbackNode가 아직 바뀌지 않은 경우, 즉 해당 task가 아직 종료되지 않은 경우 해당 함수를 다시 리턴하고, root.callbackNode가 바뀐 경우, 즉 해당 task가 종료된 경우 null을 리턴합니다. 여기서 리턴하는 값이 중요한 이유는 이 값이 Scheduler의 workLoop에서 해당 task를 resume 하는 데에 사용되기 때문입니다.</p><pre>// This is the entry point for every concurrent task, i.e. anything that<br>// goes through Scheduler.<br>function performConcurrentWorkOnRoot(root, didTimeout) {<br>  ...<br>  const originalCallbackNode = root.callbackNode;<br>  let lanes = getNextLanes(<br>    root,<br>    root === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes,<br>  );</pre><pre>  ...</pre><pre>  ensureRootIsScheduled(root, now());<br>  if (root.callbackNode === originalCallbackNode) {<br>    ...<br>    return performConcurrentWorkOnRoot.bind(null, root);<br>  }<br>  return null;<br>}</pre><p>이제 workLoop를 보겠습니다. currentTask의 callback이 fiber를 재조정하는 performConcurrentWorkOnRoot라는 사실에 주의하면서 따라가 보겠습니다. 우선 typeof callback이 function이므로 첫 번째 분기로 들어가게 되는데, 만약 task가 완료되지 않은 상태에서 해당 callback이 shouldYield에 의해 중단된 경우, 위에서 살펴본 것처럼 자기 자신을 리턴하게 되며, 이 값은 continuationCallback에 할당됩니다. 하지만 만약 callback이 모든 Fiber 작업을 마무리한 뒤에 null을 리턴했다면 해당 task는 모든 fiber 재조정 작업을 성공적으로 마무리한 것으로 간주하고 taskQueue에서 빠지게 됩니다.</p><p>즉, Scheduler의 workLoop는 taskQueue를 계속 peek 하면서 task에 대해 작업을 수행하는데 만약 해당 task의 callback의 실행결과가 함수이면 아직 실행을 마무리하지 못하고 중간에 suspend 된 것이므로 taskQueue에 남겨두고, 실행결과가 null이면 해당 task는 실행이 끝난 것으로 간주하고 taskQueue에서 pop 하는 방식으로 동작하는 것입니다.</p><pre>// workLoop<br>// 여기서의 callback은 reconciler의 performConcurrentWorkOnRoot를 의미합니다.<br>if (typeof callback === &#39;function&#39;) {<br>  currentTask.callback = null;<br>  currentPriorityLevel = currentTask.priorityLevel;<br>  const didUserCallbackTimeout = currentTask.expirationTime &lt;= currentTime;<br>  const continuationCallback = callback(didUserCallbackTimeout);<br>  currentTime = getCurrentTime();<br>  if (typeof continuationCallback === &#39;function&#39;) {<br>    currentTask.callback = continuationCallback;<br>    advanceTimers(currentTime);<br>    return true;<br>  } else {<br>    if (currentTask === peek(taskQueue)) {<br>      pop(taskQueue);<br>    }<br>    advanceTimers(currentTime);<br>  }<br>} else {<br>  pop(taskQueue);<br>}</pre><h3>Conclusion</h3><p>지금까지 React Concurrent Mode의 핵심인 Scheduler에 대해 살펴보았습니다. Concurrent Mode의 핵심은 task를 수행하다가 우선순위가 더 높은 task가 들어오면 잠깐 작업을 중단하고, 우선순위가 더 높은 task를 수행한 뒤 기존 task를 재개하는 것입니다. React는 task의 우선순위를 expirationTime으로 정하고, 이를 minHeap 기반의 priorityQueue에 넣는 방식으로 정렬합니다. 각 task의 callback은 재조정 함수인 performConcurrentWorkOnRoot가 할당되며, 해당 함수가 workLoopConcurrent를 실행하다가 shouldYield함수에 의해 interrupt 되면 Suspend 되는데, 이때는 함수 자기 자신을 리턴함으로써 taskQueue에 중단된 상태 그대로 남아있다가 다시 자기 차례가 오면 실행을 마무리하고 null을 리턴함으로써 재조정을 마치고 taskQueue에서 빠져나오게 됩니다.</p><p>다음 포스팅에서는 task의 우선순위를 결정하는 React의 방식인 LaneModel에 대해 살펴봄으로써 Concurrent Mode에 대한 이해도를 높여보도록 하겠습니다.</p><h3>Reference</h3><p><a href="https://javascript.info/event-loop">https://javascript.info/event-loop</a></p><p><a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/setImmediate">https://developer.mozilla.org/en-US/docs/Web/API/Window/setImmediate</a></p><p><a href="https://en.wikipedia.org/wiki/Min-max_heap">https://en.wikipedia.org/wiki/Min-max_heap</a></p><p><a href="https://en.wikipedia.org/wiki/Priority_queue">https://en.wikipedia.org/wiki/Priority_queue</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c887cbfe5a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Mount System Deep Dive (Sync Mode)]]></title>
            <link>https://sckimynwa.medium.com/react-mount-system-deep-dive-sync-mode-c89c1ace14af?source=rss-9ce465f93d9e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c89c1ace14af</guid>
            <category><![CDATA[q-and-a]]></category>
            <category><![CDATA[fiber]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[yeoul]]></category>
            <dc:creator><![CDATA[Yeoul]]></dc:creator>
            <pubDate>Sun, 08 Jan 2023 22:34:02 GMT</pubDate>
            <atom:updated>2023-01-08T22:34:02.774Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HpWnOdOxSoHl0Ggx.png" /></figure><h3>Overview</h3><p>이전 글들 (<a href="https://yeoulcoding.tistory.com/328">Conceptual Model of React Suspense</a>, <a href="https://yeoulcoding.tistory.com/331">Algebraic Effects of React Suspense</a>, <a href="https://yeoulcoding.tistory.com/333">Suspense SSR Architecture in React 18</a>)에 이어 Suspense의 동작 원리에 대해 Source Code Level에서 다루는 포스팅을 준비하고 있었습니다. 하지만 막상 Code Level에서 이를 분석하려고 하니 너무나 방대한 React의 개념들과 용어들(Fiber, Scheduler, Task, Lane, performUnitOfWork, Double Buffering)을 능숙하게 이해하고 있음을 전제하여야 했고, 이 모든 내용을 하나의 포스팅에 담기는 어려울 것 같다는 결론을 내렸습니다.</p><p>따라서 React18에서 이야기하는 Concurrency가 정확히 무엇인지, 그리고 Suspense가 여기에서 어떤 역할을 하는지를 Source Code Level에서 파악하기 전에 먼저 React가 “이전에”(<em>여기서 이전이란, Concurrency mode가 도입되기 전, React 17 + Fiber Architecture를 의미합니다. 코드 상에서는 이를 Sync Mode, 혹은 Legacy Mode라 칭합니다.</em>) 화면을 어떻게 렌더하고 있는지에 대해 이해해야 합니다. 이번 포스팅은 이에 관한 것입니다.</p><p>즉, 이번 포스팅에서는 Concurrency Mode가 활성화되지 않은 기존 <em>ReactDOM.render() </em>를 사용해서 화면을 렌더 할 때, 실제로 어떤 코드들이 실행되고, 어떤 단계들을 거쳐 브라우저 화면에 나타나는지를 살펴보려고 합니다.</p><h3>Double Buffering Structure</h3><blockquote><em>In computer science, multiple buffering is the use of more than one buffer to hold a block of data, so that a “reader” will see a complete (though perhaps old) version of the data, rather than a partially updated version of the data being created by a “writer”. It is very commonly used for computer display images. — wiki</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/0*cNg2NaWrskA8r9cS.png" /></figure><p>아래에서 살펴볼 React Source Code를 보면, <em>current, workInProgress, alternate</em>와 같은 용어들이 등장합니다. 이는 수십년 전부터 게임 프로그래밍에 사용되던 Double Buffering 개념을 React에 도입한 것인데, 한쪽에서 화면을 보여주는 동안(current) 다른 한쪽에서는 렌더링 작업을 진행하고(workInProgress), 렌더링 작업이 끝나면 서로 alternate로 참조하고 있는 current와 workInProgress를 서로 Switching 하는 방식으로 동작하는 것을 의미합니다. 따라서 코드를 살펴보다가 current, workInProgress, alternate와 같은 참조들이 등장한다면 “이는 위의 Double Buffering Mode를 위한 것이고, 실제 렌더링 작업은 workInProgress에서 진행한 뒤에, 작업이 끝나면 이를 alternate참조를 통해 current로 변경하는구나”라고 이해하면 됩니다. (current, workInprogress는 모두 FiberNode를 가리킵니다.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/0*v1qX61SXxHBgw2ib.png" /></figure><h3>Phase of React</h3><blockquote><em>Imagine that your components are cooks in the kitchen, assembling tasty dishes from ingredients. In this scenario, React is the waiter who puts in requests from customers and brings them their orders. This process of requesting and serving UI has three steps:<br>- Triggering a render (delivering the guest’s order to the kitchen)<br>- Rendering the component (preparing the order in the kitchen)<br>- Committing to the DOM (placing the order on the table)</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/0*9sgT4XShOXmlZpbG.png" /></figure><p>React가 우리의 JSX Element를 화면에 렌더링하는 과정은 크게 3가지로 나눌 수 있습니다. (<em>다시 한번 강조하지만, 이 포스팅은 Concurrent Mode에 대한 내용이 아니며, Sync Mode(Legacy Mode)를 기준으로 설명합니다.</em>) Mount나 Update를 위해 ReactDOM.render()를 호출하는 <strong>Trigger Phase</strong>, 컴포넌트를 Rendering하는 <strong>Render Phase</strong>, 그리고 Render된 Fiber Node를 실제 화면에 반영하고 Effect를 소비하는 <strong>Commit Phase</strong>입니다.</p><p>여기서의 Render는 React가 렌더 할 JSXElement들을 Fiber Node로 만들고, Tree 구조를 만들고, 각각의 Task들을 스케줄 하고, Reconcile(재조정)하는 것까지를 포함합니다. <strong>실제로 화면에 이 Fiber Node를 HTML Element로 반영하는 DOM Update 단계는 Render 단계에서 수행하지 않으며, 이는 Commit 단계에서 수행하게 됩니다.</strong></p><p>initialMount를 다룰 때에는 ReactDOM.render가 단 한번 호출되게 되므로 Trigger Phase는 건너뛰고, Render Phase부터 소스코드 분석을 시작해보도록 하겠습니다.</p><h3>Source Code Deep Dive</h3><p><a href="https://reactjs.org/docs/how-to-contribute.html#development-workflow">React Contribution Guide</a>를 살펴보면 React Source Code가 어떻게 구성되어 있고, 어떻게 빌드하고 어떻게 테스트하고 어떻게 개발하면 좋은지에 대한 공식적인 가이드가 나와 있습니다. 이 가이드대로 실습 환경을 구성한 뒤에 Chrome Debugger를 사용해서 실제로 React가 어떤 함수들을 호출하며 동작하는지 살펴보도록 하겠습니다. 테스트에 사용한 파일은 아래의 dev.html 파일이며, 원래 Code에는 h1 태그 하나만 있지만, Tree구조에서 Child Element가 제대로 렌더링 되는지를 확인하기 위해 이를 아래와 같이 수정해서 사용하도록 하겠습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/218/0*z4z_v-075yxQS80d.png" /></figure><p><a href="https://github.com/facebook/react/blob/main/fixtures/packaging/babel-standalone/dev.html">https://github.com/facebook/react/blob/main/fixtures/packaging/babel-standalone/dev.html</a></p><pre>&lt;html&gt;<br>  &lt;body&gt;<br>    &lt;script src=&quot;../../../build/node_modules/react/umd/react.development.js&quot;&gt;&lt;/script&gt;<br>    &lt;script src=&quot;../../../build/node_modules/react-dom/umd/react-dom.development.js&quot;&gt;&lt;/script&gt;<br>    &lt;script src=&quot;https://unpkg.com/babel-standalone@6/babel.js&quot;&gt;&lt;/script&gt;<br>    &lt;div id=&quot;container&quot;&gt;&lt;/div&gt;<br>    &lt;script type=&quot;text/babel&quot;&gt;<br>      ReactDOM.render(<br>        &lt;h1&gt;<br>          &lt;span&gt;<br>            &lt;span&gt;Yeoul&lt;/span&gt;<br>            &lt;span&gt;<br>              &lt;i&gt;Coding&lt;/i&gt;<br>            &lt;/span&gt;<br>          &lt;/span&gt;<br>        &lt;/h1&gt;,<br>        document.getElementById(&#39;container&#39;)<br>      );<br>    &lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>해당 화면을 렌더하고 Performance Recording을 한 뒤 Performance Tab을 살펴보면 다음과 같이 브라우저가 화면을 paint 하기 전에 많은 function call들이 발생하고 있음을 알 수 있습니다. 자세히 살펴보면, <em>render, performUnitOfWork, legacyCreateRootFromDOMContainer</em> 등의 여러 함수 호출들이 연쇄적으로 일어나고, 마지막에 <em>appendChild</em>가 호출되어 DOM을 업데이트하면 브라우저에 이 내용물이 반영되는 흐름인 것을 알 수 있습니다.</p><p>이제 여기에 각종 break point를 걸어가면서 React가 화면을 렌더 하는 동안 어떤 과정들을 거치는지를 알아보도록 하겠습니다. 함수 코드를 따라가다 보면 수많은 Detail과 조건문, 용어들이 나오지만 이번 포스팅에서는 sync mode에서의 initialMount를 설명하기 위해 필요한 부분만 따라가도록 하겠습니다. (거치지 않는 분기와 에러 처리, effect를 처리하는 부분등에 대한 내용은 다루지 않습니다.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_OEArDZCaGwrdDun.png" /></figure><h3>Trigger &amp; Render Phase</h3><p>HTML Source Code 상에서도 확인이 가능하듯, 가장 먼저 수행되는 함수는 <em>ReactDOM.render입니다.</em> 여기서는 <em>legacyRenderSubtreeIntoContainer</em>를 호출하고 그 결과를 리턴하는데, 이때 넘겨주는 매개변수는 render호출 시 넘겨준 h1 element와 container(react에서 &lt;div id=”container”&gt;으로 넘겨주는) element입니다.</p><blockquote><em>element = h1 react element<br>container = div#container (일반적으로 &lt;div id=”root”&gt;&lt;/div&gt;로 표현되는 container element)</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KgBZ4xI5D0uapGhI.png" /></figure><p><em>legacyRenderSubtreeIntoContainer</em>는 <em>legacyCreateRootFromDOMContainer</em>를 호출해서 rootFiberNode를 생성하고 이를 리턴합니다. 여기서의 rootFiberNode는 그대로 가장 먼저 불린 render 함수의 리턴값이 됩니다. 중간에 여러 조건문들이 있지만 initialMount때에는 container element에 _reactRootContainer가 없는 상황이므로 <em>legacyCreateRootFromDOMContainer</em></p><p>만 호출한 뒤 종료합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3FpkJcyvAG-d8_8w.png" /></figure><p><em>legacyCreateRootFromDOMContainer</em>에서는 위에서 말한 대로 rootFiberNode를 생성합니다. 그리고 container element의 _reactRootContainer property를 선언하고 여기에 이 값을 할당합니다. 이 부분의 코드를 거치게 되면 콘솔에서 container element의 _reactRootContainer property를 조회할 수 있고, 이 값은 FiberRootNode 타입의 객체입니다. 이렇게 container element를 업데이트하고 <em>updateContainer</em>를 호출합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sInfM0tx6W7A1jhZ.png" /></figure><p><em>updateContainer</em>에서는 해당 RootFiberNode를 스케줄 하기 위해 <em>scheduleUpdateOnFiber</em>를 호출합니다. (<em>위에 createUpdate, enqueueUpdate 관련된 내용이 있는데, 이 부분은 Lane에 관한 것으로, SyncMode에서는 크게 상관이 없으므로 이번 포스팅에서는 넘어가도록 하겠습니다.</em>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*afoLWOmFdR0qXGUw.png" /></figure><p><em>scheduleUpdateOnFiber</em>는 동작이 조금 독특한데, 우선 실제로 React가 Fiber 단위로 렌더 작업을 수행하기 위한 엔트리포인트인 <em>performSyncWorkOnRoot</em>를 <em>scheduleLegacySyncCallback</em>이라는 함수를 통해 스케줄 합니다. 즉, 렌더링 작업은 <em>performSyncWorkOnRoot</em>가 호출되면서부터 시작되며, 이 함수를 호출하기 위한 스케줄링을 <em>scheduleLegacySyncCallback</em>을 통해 진행한다는 의미입니다. <strong>바로 아래에 <em>scheduleMicrotask</em>와 <em>flushSyncCallbacks</em> 함수가 있음을 유의하면서 이 <em>scheduleLegacySyncCallback</em> 함수를 살펴보도록 하겠습니다.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gPOz0gxRmzR8A4i3.png" /></figure><p><em>scheduleLegacySyncCallback</em> 함수는 그냥 단순히 넘어온 callback(<em>여기서는 performSyncWorkOnRoot. 즉 실제로 컴포넌트를 render 하는 로직의 entrypoint</em>)를 <em>scheduleSyncCallback</em>에 넘겨주는 역할을 할 뿐입니다. 중요한 부분은 <em>scheduleSyncCallback</em>인데, 이 함수는 전역 변수인 syncQueue(Array)를 생성하고, 여기에 callback을 push 하고 종료합니다. 이 함수가 이렇게 syncQueue에 <em>performSyncWorkOnRoot</em>를 push만 하고 종료된다면 push된 callback은 어느 시점에 실행되는 걸까요?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ak2QC66Cv3FZRnc-.png" /></figure><p>위에 <em>scheduleUpdateOnFiber</em>를 다루면서 <em>scheduleMicrotask</em>와 <em>flushSyncCallbacks</em>를 유의해야 한다고 언급했었는데, 바로 이 부분이 이 syncQueue에 들어있는 callback을 처리하는 부분입니다. <em>scheduleUpdateOnFiber</em>는 <em>scheduleLegacySyncCallback</em>함수를 호출해서 syncQueue에 <em>performSyncWorkOnRoot</em>를 callback으로 push 한 뒤에 <em>flushSyncCallbacks</em>라는 함수를 microtask에 스케줄 합니다. 이는 말 그대로 <em>flushSyncCallbacks</em>라는 함수를 microtask로 등록한 뒤에 브라우저의 Event Loop를 사용해서 이를 실행하겠다는 의미입니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/0*YpWs1QlsbwdD8-uU.png" /></figure><p><em>scheduleUpdateOnFiber</em>의 호출이 끝난 뒤, 브라우저가 microtask를 처리하는 시점에 이 <em>flushSyncCallbacks</em> 함수가 불리게 되며 이 함수는 아래와 같이 callback을 실행하고 종료합니다. 바로 이 시점에 렌더링을 처리하는 <em>performSyncWorkOnRoot </em>함수가 호출되는 것입니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4iajPeEMD3j4cNYG.png" /></figure><h3>Wrap Up Before performSyncWorkOnRoot</h3><p>지금까지의 단계를 도표로 정리해보면 다음과 같습니다. 처음 Render를 호출하고 난 이후부터 실제로 렌더링 작업을 시작하기 위한 workLoopSync가 불리는 단계까지를 살펴보았으며, 이 단계까지 오는 동안 FiberRootNode와 _reactRootContainer가 생성되었고, 작업을 시작하기 위한 <em>performSyncWorkOnRoot</em>가 브라우저의 event loop에 microtask로 등록되었다가 실행되는 것을 살펴보았습니다. 지금부터는 <em>performSyncWorkOnRoot</em>부터 시작해서 실제로 React가 어떻게 컴포넌트들을 렌더 하는지를 살펴보도록 하겠습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/0*HYNV2ngdEwmel954.png" /></figure><h3>Rendering Fiber Tree</h3><p><em>performSyncWorkOnRoot</em>에서는 크게 2가지의 작업을 수행합니다. Fiber Tree Structure를 렌더링 하기 위해 renderRootSync를 호출하는 부분 (Render Phase)과, Render가 완료된 후 돌아와서 이를 DOM에 반영하기 위해 commitRoot를 호출하는 부분 (Commit Phase). 지금은 Render Phase에 대한 내용을 설명하고 있으므로, commitRoot를 호출하는 부분은 아래에서 다시 살펴보도록 하고, 우선 <em>renderRootSync</em>에 대해서만 살펴보도록 하겠습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/0*S1nkn3BxarL1kCx8.png" /></figure><p>renderRootSync에서는 이 글의 제일 위에서 살펴보았던 Double Buffering 구조를 만들기 위해 current Fiber Node의 alternate인 workInProgress Node를 생성하는 함수인 <em>prepareFreshStack</em>을 호출하게 됩니다. <em>prepareFreshStack</em>에서는 <em>createWorkInProgress</em>를 호출하여 FiberRootNode의 workInProgress Node를 생성합니다. <strong>생성 후, root의 current.alternate는 workInProgress로, workInProgress.alternate는 current의 매핑을 만들어주어 아래와 같은 Double Buffering 구조</strong>를 만들어 줍니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/0*cz97ZH9KOD9rm3SR.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*weYXXe2XPsMAW-bs.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cZuMrr_ckbjPV_e9.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fAwaYqv53-QBEFhl.png" /></figure><p>이렇게 FiberRootNode에 대해서 workInProgress가 생성된 이후에는 <em>renderRootSync</em>로 돌아와 <em>workLoopSync</em>를 호출하여 workInProgress fiber에 대한 작업을 시작하게 됩니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/0*eYDrbwTil_z9aBMx.png" /></figure><p>workLoopSync는 비교적 간단한 구조로 되어 있습니다. <strong>workInProgress가 null이 될 때까지 workInProgress FiberNode에 대해서 performUnitOfWork를 수행</strong>하게 되며, 여기서의 unit은 incremental rendering을 위한 단일 Fiber Node가 됩니다. (뒤에서 살펴보겠지만 하나의 <em>performUnitOfWork</em>를 수행할 때마다 workInProgress 변수는 다음 Fiber Node의 workInProgress를 가리키도록 재할당 되기 때문에 이 <em>workLoopSync</em>가 종료되는 시점에는 렌더링해야 할 모든 Fiber가 처리된 상태가 됩니다.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QHwtjXehxbLOAXPF.png" /></figure><p><em>performUnitOfWork</em>는 React Rendering 알고리즘의 핵심 로직입니다. 넘어온 workInProgress FiberNode를 받아서 <em>beginWork</em>를 호출해서 작업을 시작합니다. <em>beginWork</em>가 리턴하는 값은 workInProgress Node의 children이기 때문에 이 performUnitOfWork는 더 이상의 children이 없을 때까지 이 작업을 수행할 수 있습니다. 더 이상의 children이 없는 경우, <em>completeUnitOfWork</em>를 호출해서 해당 노드로부터의 렌더링을 마무리합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/233/0*vnXOZGsiYAgmBmay.png" /></figure><p>위의 내용을 dev.html의 element들이 렌더링 되는 예시를 통해 가볍게 확인해 보겠습니다.</p><ul><li>처음 performUnitOfWork의 매개변수로 들어가는 workInProgress는 FiberRootNode를 의미합니다. 바로 h1을 처리하는 것이 아닌 FiberRootNode를 먼저 처리하는 점에 주의해야 합니다.</li><li>처음 beginWork에서 리턴되어 next에 할당되는 값은 FiberRootNode의 child인 h1입니다. next = h1인 상태이므로 다음에 처리할 workInProgress가 next인 h1 FiberNode로 변경되고 다시 performUnitOfWork를 실행합니다.</li><li>h1노드가 처리되고 다음 next에 할당되는 값은 span입니다. 위와 동일한 순서대로 span을 처리하고 그다음 span을 처리하고 마지막 “Yeoul”이 담겨있는 TextNode까지 처리하고 나면 next = null이 되고 completeUnitOfWork가 호출됩니다.</li><li>completeUnitOfWork가 호출되고 나면 최하단 Leaf Node (여기서는 TextNode)부터 다시 거슬러 올라가면서 해당 FiberNode에 sibling Node가 있는지를 확인합니다. 아직 “Coding”이 들어있는 span 노드가 렌더링 되지 않았으므로 이 span Node를 workInProgress로 변경한 뒤에 이 작업을 수행합니다.</li><li>이렇게 모든 노드를 순회하고 나면 performUnitOfWork가 종료되고, 렌더해야 하는 모든 Element가 FiberNode와 stateNode(reactElement)의 Tree 형태로 저장됩니다.</li><li>이 상태에서 Commit Phase에 진입하며, Commit Phase에서 이 FiberNode와 StateNode를 기준으로 DOM에 화면을 그리게 됩니다.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tiM5kzd_UJpP_yPI.png" /></figure><p><em>beginWork</em>에서는 넘어온 workInProgress Node의 tag를 보고 HostRoot / HostComponent 등의 타입을 판단합니다. 가장 처음에 넘어오는 workInProgress는 FiberRootNode이기 때문에 HostRoot 타입에 걸리게 되고, 다음(h1)부터는 하위 Element인 HostComponent에 걸리게 됩니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-15gjT1sf4g0Z_ru.png" /></figure><p><em>updateHostRoot</em> 함수에서는 넘어온 workInProgress Fiber Node에 대해 <em>reconcileChildren</em>을 호출해서 각 Children에 대한 FiberNode를 생성하게 됩니다. 이미 FiberNode가 있으면 <em>reconcileChildFibers</em>가, 아직 생성되지 않았으면 <em>mountChildFibers</em>가 호출됩니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*reXUQRGYEfbCdSo6.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*intdP8xwKgIJcDOR.png" /></figure><p><em>reconcileChildFibers</em>에서는 child의 element 타입을 보고 어떤 함수를 호출할지를 결정하는데, h1, span, textnode 등은 전부 <strong>REACT_ELEMENT_TYPE</strong>에 속하므로 <em>reconcileSingleElement</em>가 호출됩니다. 만약 newChild가 단일 Element가 아니라 Array일 때, 그러니까 dev.html의 바깥 span 태그 안에 들어가 있는 2개의 span 태그와 같이 React Element의 배열로 들어올 때는 별도로 <em>reconcileSingleElement</em>가 아닌 <em>reconcileChildrenArray</em>를 호출해서 fiber node 사이의 sibling 관계를 형성하게 됩니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/0*GBQ3rIXUO9cxlTBs.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/0*mNYVD5LEO36n9zqS.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/0*xfZZTNXd08HVxJY_.png" /></figure><p>여기까지 생성하고 나면 <em>performSyncWorkOnRoot</em>로 제어권이 다시 넘어오게 되는데, 이제 여기서는 <em>commitRoot</em>를 호출함으로써 Commit Phase로 진입하게 됩니다. 여기까지의 과정이 Render Phase에 대한 코드의 간략한 개요이며, 이 과정이 마무리되었을 때, 리액트는 다음과 같은 Fiber Tree Structure를 얻게 됩니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/0*P4SKwL9IcxOvokAp.png" /></figure><h3>Commit Phase</h3><p>commit phase는 render phase에 비해 비교적 간단합니다. 이번 포스팅에서 다룰 부분은 아니지만 commit Phase에서 effect를 handle 하기 때문에 이 단계에서 useEffect의 callback들이 호출됩니다. React는 <em>commitRoot</em>로부터 시작되는 연쇄적인 함수 호출을 통해 결국 host의 DOM Element에 대해 <em>appendNode</em>를 호출하게 되며, 여기서 실제 DOM 노드를 업데이트하게 되고, 비로소 우리가 보는 화면에 DOM Node가 보이게 됩니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VlZ6vRkS31sxI2rH.png" /></figure><p><em>performSyncWorkOnRoot</em>에서 <em>renderRootSync</em> 함수의 호출이 끝나고 Fiber Tree 구조가 완성되면 이어서 <em>commitRoot</em>를 호출합니다. 이후 <em>commitRoot -&gt; commitRootimpl -&gt; commitMutationEffects -&gt; commitMutationEffectsOnFiber -&gt; commitReconcilationEffects -&gt; commitPlacement -&gt; insertOrAppendPlacementNode -&gt; appendNode</em>의 흐름을 거쳐 DOM Node에 최종적으로 반영됩니다. 정확히는 <em>commitMutationEffects</em> 호출이 완료되었을 때, <em>requestPaint</em>() 호출을 통해 브라우저에게 paint를 요청함으로써 화면에 DOM Node를 그리게 됩니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/0*QuZGK9GGnlYZv8bi.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Dd7ZgLlVTJcyaUBe.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wKHTyhjld5qAlPy5.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*a9S3pRiGBcXCjnVQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*nsVj4v9Q_dpLuxmC.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sKQ0C-TS97lVdyqt.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/0*icAE2nQxgB6YrCYS.png" /></figure><h3>Summary</h3><p>지금까지 매우 긴 여정을 거쳐 ReactDOM.render를 호출했을 때 실제로 React가 어떻게 FiberNode를 생성하고, 이를 순회하여 렌더 하고, 화면에 반영하는지를 살펴보았습니다. 굉장히 많은 함수 호출들이 여러 가지 상호작용을 통해 이루어지면서 로직을 복잡하게 만들었는데, 앞서 살펴본 내용들을 순서대로 나타내 보면 다음과 같습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ISIWfmLJ_SRNlhUi.png" /></figure><p>React의 Fiber Structure와 기존 렌더링 로직에 대한 이해가 없이 바로 React의 Concurrency Mode를 이해하는 일은 여간 어려운 것이 아닙니다. React Core Team이 기존의 구조로부터 수년간 안정적인 업그레이드를 위해 노력해온 결과물이기 때문에 Concurrency Mode의 구현도 기존 Fiber Structure와 Sync Mode에 대한 이해로부터 출발합니다.</p><p>다음 포스팅부터는 이 Sync Mode에 대한 이해로부터 출발해서 Concurrency Mode가 무엇인지, 오늘 살펴보았던 기존의 렌더링 방식과는 어떤 것인지를 알아보고, Scheduler, Lane Model 등 Concurrency Mode의 이해에 핵심이 되는 내용들을 살펴보려고 합니다.</p><h3>Reference</h3><p><a href="https://github.com/facebook/react">https://github.com/facebook/react</a></p><p><a href="https://tv.naver.com/v/23652451#comment_focus">https://tv.naver.com/v/23652451</a></p><p><a href="https://beta.reactjs.org/learn/render-and-commit">https://beta.reactjs.org/learn/render-and-commit</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c89c1ace14af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Suspense SSR Architecture in React 18]]></title>
            <link>https://blog.mathpresso.com/suspense-ssr-architecture-in-react-18-ec75e80eb68d?source=rss-9ce465f93d9e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec75e80eb68d</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[server-side-rendering]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[febe]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Yeoul]]></dc:creator>
            <pubDate>Fri, 23 Sep 2022 00:56:09 GMT</pubDate>
            <atom:updated>2023-02-22T04:45:21.951Z</atom:updated>
            <content:encoded><![CDATA[<h4>React 18의 Suspense가 SSR에 가져올 변화에 대해서 살펴봅니다.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tv10G2XzX-6hHFJBKVXDhQ.png" /></figure><h3>Introduction</h3><p>React Working Group(<a href="https://github.com/reactwg">reactwg</a>)에서 React Core Team의 Dan Abramov는 React 18의 주요 Feature 중 하나인 Suspense가 SSR Architecture의 구조적인 성능 개선을 위해 어떤 역할을 하게 될지에 대한 내용을 설명했습니다. [<a href="https://github.com/reactwg/react-18/discussions/37">discussion link</a>] 이번 포스팅은 해당 Discussion을 번역해서 현재 SSR이 어떻게 이루어지고 있는지, React 18의 Suspense가 이를 어떻게 구조적으로 개선했는지에 대해 살펴보려고 합니다. (원문 링크는 discussion link나 아래 Reference를 참고해주세요)</p><p>이 글은 새로운 서버사이드 렌더링 아키텍처와 디자인, 그리고 문제 해결 방법에 대한 High-Level Overview입니다. 자세한 구현 사항은 이후 포스팅을 통해 살펴보도록 하겠습니다.</p><h3>What is SSR?</h3><p>유저가 애플리케이션을 로드했을 때, 우리는 가능한 한 빠르게 fully-interactive 한 페이지를 보여주고 싶을 것입니다. 아래 일러스트레이션에서 초록색으로 칠해진 영역은 페이지 상에서 상호작용이 가능하다(interactive)는 것을 나타냅니다. 다른 말로 하면, 해당 영역에 Javascript 이벤트 핸들러가 붙어있는 상태이고, 버튼을 눌렀을 때, 상태를 업데이트하는 등의 Reactive 한 동작들을 수행할 수 있다는 것을 의미합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1oDQsxC2SYGAEQWE.png" /></figure><p>하지만, 자바스크립트가 “모두” 로드되기 전까지 사용자는 페이지에 대한 상호작용을 할 수 없습니다. 애플리케이션의 규모가 작지 않다면(non-trivial), 로딩 시간의 대부분은 애플리케이션 코드를 다운로드하는 데 사용될 것입니다. 만약 SSR을 사용하지 않는다면 자바스크립트가 로딩되는 동안 유저는 빈 페이지(blank page)를 보게 될 것입니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HxOdkeV5_xdwfpPf.png" /></figure><p>이것은 좋은 사용자 경험이 아니며(특히 자바스크립트 로딩 시간이 오래 걸리는 저사양 디바이스에서 그렇습니다) 이러한 이유로 SSR(서버 사이드 렌더링)이 권장됩니다. SSR은 React Component를 서버에서 HTML로 렌더링해서 유저에게 내려주는 방식으로 동작합니다. 이렇게 내려온 HTML은 브라우저에서 기본적으로 제공하는 link, form input 등과 같은 상호작용 요소를 제외하고는 interactive 하지는 않지만, 유저들로 하여금 자바스크립트가 로딩되는 동안 무언가를 볼 수 있게 해줍니다.</p><p>아래 일러스트레이션에서 회색 영역은 아직 상호작용을 할 수 없다(not fully interactive yet)는 것을 의미합니다. 애플리케이션의 자바스크립트가 아직 로드되지 않았기 때문에 해당 영역에 버튼이 있고, 해당 버튼을 눌렀을 때 State가 업데이트되는 것이 기대되지만, 실제로는 아무 일도 일어나지 않습니다. 하지만, 콘텐츠가 많은 웹사이트의 경우 자바스크립트가 로드되는 동안에 유저는 콘텐츠를 읽을 수 있으므로 SSR을 사용하는 것이 매우 유용하며, 권장됩니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Z_Ctudr34zzrTt7W.png" /></figure><p>React와 애플리케이션 코드가 모두 로드되고 나면, 이미 존재하는 회색 영역의 HTML을 상호작용이 가능하도록 만들어야 합니다.</p><blockquote><em>You tell React: “Here’s the App component that generated this HTML on the server.<br>Attach event handlers to that HTML!”</em></blockquote><p>리액트는 메모리상에 컴포넌트를 렌더링하지만, DOM 노드를 생성하지 않고(이미 노드가 문서에 존재하므로) 이미 존재하는 HTML에 이벤트 핸들러와 같은 로직을 붙여줍니다. 이렇게 React가 로드되고 나서 컴포넌트를 메모리에 렌더링하고 이벤트 핸들러를 붙이는 일련의 과정을 Hydration이라고 합니다. 이렇게 Hydration이 끝나고 나면 나머지는 “평소의 리액트”(React as usual)입니다. 컴포넌트는 상태 값을 변경할 수도 있고, 클릭에 반응할 수도 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*B6SLcKmUdbovFKo-.png" /></figure><p>SSR는 “마법”처럼 보일 수 있겠지만, 이 과정 자체로는 애플리케이션의 상호작용을 더 빠르게 만들지는 않습니다. 대신, 애플리케이션에서 상호작용이 없는(non-interactive version) 부분을 더 빠르게 볼 수 있게 해서 유저들이 자바스크립트가 로드되는 동안 정적 콘텐츠를 볼 수 있도록 해줍니다. SSR은 특히 네트워크 상태가 좋지 않은 유저들에게 큰 차이를 가져오고 유저가 인식하는 성능(perceived performance) 향상을 가져옵니다. 또한 쉬운 인덱싱과 빠른 속도로 Search Engine Optimization에도 도움을 줍니다.</p><h3>What Are the Problems with SSR Today?</h3><p>이러한 SSR은 많은 장점들을 가져왔지만, 근본적인 측면에서의 문제를 해결하지 못합니다.</p><h4>You have to fetch everything before you can show anything</h4><p>SSR이 가진 문제점 중 하나는 컴포넌트가 “데이터를 기다리도록” 하지 않는다는 것입니다. 현재의 SSR 관련 API를 사용하면 HTML을 렌더하는 시점에 서버에서 컴포넌트 렌더를 위해 필요한 모든 데이터가 준비되어야 하고, 이 방법은 매우 비효율적입니다.</p><p>예를 들어 댓글이 있는 포스트를 렌더링하고 싶다고 가정해보겠습니다. 댓글을 빠르게 보여주는 것은 중요하기 때문에 서버사이드 렌더링에 포함시켜서 출력하고 싶지만, 프론트엔드 개발자가 제어할 수 없는 DB나 API 레이어에서의 속도가 느려서 이 부분은 건드릴 수 없는 상황이라고 한다면 이런 경우 힘든 결정을 내려야 합니다. 댓글 컴포넌트를 최초 HTML 렌더링에서 제외한다면 유저는 자바스크립트가 완전히 로드가 되고, React가 클라이언트 쪽에서 해당 컴포넌트를 다시 DOM에 그릴 때까지 컴포넌트를 볼 수 없게 될 것입니다. 댓글 컴포넌트를 최초 HTML 렌더링에 포함시킨다면 전자의 경우보다는 댓글 컴포넌트를 빠르게 보여줄 수는 있겠지만, 댓글 데이터를 가져오고 전체 트리를 렌더하기 전까지 나머지 HTML을 전송하는 것을 지연시켜야 할 것입니다. (이는 네비게이션바, 사이드바, 포스팅 본문 등의 내용을 포함합니다.)</p><h4>You have to load everything before you can hydrate anything</h4><p>자바스크립트 코드가 로드된 후 리액트는 HTML을 “Hydrate”하고, 이를 통해 페이지는 상호작용이 가능한 상태가 됩니다. 리액트는 서버에서 생성된 HTML을 순회(walk)하며 여기에 이벤트 핸들러를 부착시킬 것입니다. 이 과정이 제대로 동작하기 위해서는 “브라우저에서 컴포넌트를 기반으로 생성된 트리”와 “서버에서 생성된 트리”가 일치해야 합니다. 그렇지 않으면 리액트는 두 트리를 “일치시킬 수 없게” 됩니다. 이러한 과정의 가장 안타까운 점은 Hydration이 시작하기 전에 클라이언트에 모든 컴포넌트에 대한 자바스크립트가 로드되어야 한다는 것입니다.</p><p>예를 들어, 댓글 위젯이 많은 양의 복잡한 상호작용 로직을 가지고 있고, 자바스크립트를 로드하기 위해 꽤 오랜 시간이 걸린다고 가정해보겠습니다. 이러한 경우에 우리는 또다시 힘든 결정을 내려야 합니다. 유저에게 댓글을 빨리 보여주기 위해 SSR을 사용하는 것이 좋을 것입니다. 하지만 오늘날의 Hydration 로직 하에서는 네비게이션바, 사이드바, 그리고 포스트 본문들 모두가 댓글 위젯에 대한 코드가 로드될 때까지 Hydration을 할 수 없게 됩니다.</p><p>물론 Code Splitting을 통해 컴포넌트를 따로따로 로드할 수 있지만, 이렇게 분리된 컴포넌트는 최초 Hydration에 포함되지 않으며 리액트는 Hydration 단계에서 해당 컴포넌트를 삭제할 것입니다.</p><h4>You have to hydrate everything before you can interact with anything</h4><p>Hydration 자체에도 비슷한 문제가 있습니다. 리액트는 Hydration을 처리할 때, 도중에 멈추지 않고 모든 작업을 한 번에 처리합니다. (React hydrates the tree in a single pass) 이는 서버사이드 렌더 된 컴포넌트 중 어느 하나라도 상호작용이 가능한 상태가 되기 위해서는 모든 컴포넌트가 Hydration 되어야 한다는 것을 의미합니다.</p><p>예를 들어, 댓글 위젯 쪽에 굉장히 시간이 오래 걸리는 렌더링 로직이 들어있다고 가정해보겠습니다. 한번 Hydration이 시작되면, 전체 컴포넌트 트리가 완전히 Hydration 되기 전까지 유저는 댓글 위젯뿐 아니라 네비게이션바, 사이드바, 포스팅 본문들 모두와 상호작용할 수 없습니다. 특히 네비게이션바의 경우 유저가 이 페이지 자체에서 떠나고 싶지만, Hydration이 진행되는 동안에는 해당 컴포넌트와 상호작용을 할 수 없으므로 더 이상 보고 싶지 않은 페이지에 남아 있어야 하는 경우가 생기게 됩니다.</p><h4>How can we solve these problems?</h4><p>위에서 얘기한 3가지 문제점들에는 공통점이 하나 있는데, 그것은 어떤 동작을 “이른 시기부터 수행하거나”(다른 작업들을 모두 블로킹하기 때문에 사용자 경험을 훼손하는 경우), “나중에 수행하거나”(시간을 낭비하기 때문에 사용자 경험을 훼손하는 경우)의 둘 중 하나를 선택하도록 강요한다는 것입니다.</p><p>이러한 문제가 발생하는 이유는 이 모든 과정들이 “Concurrent” 하게 이루어지지 못하기 때문입니다. (Waterfall) 서버에서 데이터를 가져오는 과정이 모두 끝나야 서버에서 HTML로 렌더링할 수 있고 클라이언트에 모든 자바스크립트 코드가 렌더링 된 후에야 Hydration을 수행할 수 있고, 모든 Hydration이 끝나야 임의의 컴포넌트가 상호작용이 가능한 상태가 될 수 있다는 것입니다. 그리고 이 Waterfall 방식의 SSR 동작이 이 모든 것을 비효율적으로 만드는 이유입니다. 이에 대해 React Core Team이 제시하는 해결책은 이 모든 과정을 “Concurrent” 하게 만드는 것입니다. 즉, 앞에서 언급한 작업을 쪼개, 전체 애플리케이션이 아닌 각각의 부분들에 대해 이 단계들을 수행할 수 있게 하는 것입니다. 그리고 이 문제를 React 18의 Suspense를 사용해서 해결할 수 있습니다.</p><h3>React 18: Streaming HTML and Selective Hydration</h3><p>Reat18에서는 Suspense를 통해 다음 2가지 SSR Feature를 사용할 수 있습니다.</p><ul><li><strong>Streaming HTML</strong> on the server. To opt into it, you’ll need to switch from renderToString to the new renderToPipeableStream method, as <a href="https://github.com/reactwg/react-18/discussions/22">described here</a>.</li><li><strong>Selective Hydration</strong> on the client. To opt into it, you’ll need to <a href="https://github.com/reactwg/react-18/discussions/5">switch to hydrateRoot</a> on the client and then start wrapping parts of your app with &lt;Suspense&gt;.</li></ul><p>해당 기능들이 어떤 역할을 하고, 더 나아가 어떤 문제를 해결하는지 확인하기 위해 예제를 살펴보도록 하겠습니다. (예제는 앞에서도 계속 사용되었던 댓글 위젯에 대한 내용을 사용합니다.)</p><h4>Streaming HTML before all the data is fetched</h4><p>React 18은 페이지의 부분을 Suspense로 감싸서 특정 컴포넌트가 준비되기 전까지 fallback UI를 보여주도록 할 수 있습니다. 아래의 예시에서 “Comments” 컴포넌트를 “Suspense”로 감싸줌으로써, 리액트에게 댓글 컴포넌트를 기다리지 말고 우선 나머지 페이지에 대해서 HTML을 Streaming 할 수 있게 도와줍니다</p><pre>&lt;Layout&gt;<br>  &lt;NavBar /&gt;<br>  &lt;Sidebar /&gt;<br>  &lt;RightPane&gt;<br>    &lt;Post /&gt;<br>    &lt;Suspense fallback={&lt;Spinner /&gt;}&gt;<br>      &lt;Comments /&gt;<br>    &lt;/Suspense&gt;<br>  &lt;/RightPane&gt;<br>&lt;/Layout&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8lcpVjIcqJdmxxbn.png" /></figure><p>이렇게 최초로 서버에서 렌더된 HTML에는 댓글 컴포넌트 대신에 fallback ui인 spinner가 들어가 있게 됩니다.</p><pre>&lt;main&gt;<br>  &lt;nav&gt;<br>    <em>&lt;!--NavBar --&gt;</em><br>    &lt;a href=&quot;/&quot;&gt;Home&lt;/a&gt;<br>   &lt;/nav&gt;<br>  &lt;aside&gt;<br>    <em>&lt;!-- Sidebar --&gt;</em><br>    &lt;a href=&quot;/profile&quot;&gt;Profile&lt;/a&gt;<br>  &lt;/aside&gt;<br>  &lt;article&gt;<br>    <em>&lt;!-- Post --&gt;</em><br>    &lt;p&gt;Hello world&lt;/p&gt;<br>  &lt;/article&gt;<br>  &lt;section id=&quot;comments-spinner&quot;&gt;<br>    <em>&lt;!-- Spinner --&gt;</em><br>    &lt;img width=400 src=&quot;spinner.gif&quot; alt=&quot;Loading...&quot; /&gt;<br>  &lt;/section&gt;<br>&lt;/main&gt;</pre><p>이 상황에서 서버 쪽에서 댓글 데이터가 준비되면, 리액트는 동일한 Stream에 추가되는 HTML과, 해당 HTML을 올바른 “위치”에 주입하기 위한 작은 inline “script” 태그를 보내줍니다.</p><pre>&lt;div hidden id=&quot;comments&quot;&gt;<br>  <em>&lt;!-- Comments --&gt;</em><br>  &lt;p&gt;First comment&lt;/p&gt;<br>  &lt;p&gt;Second comment&lt;/p&gt;<br>&lt;/div&gt;<br>&lt;script&gt;<br>  <em>// This implementation is slightly simplified</em><br>  document.getElementById(&#39;sections-spinner&#39;).replaceChildren(<br>    document.getElementById(&#39;comments&#39;)<br>  );<br>&lt;/script&gt;</pre><p>결과적으로 클라이언트에서 리액트 자체를 로드하기도 전에 늦게 도착한 댓글 부분의 HTML을 보여줄 수 있게 됩니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oYg-utLL7hKBOag_.png" /></figure><p>이러한 방법은 위에서 이야기한 “<em>첫 번째 문제(You have to fetch everything before you can show anything)</em>”를 해결합니다. 이제 무언가를 보여주기 위해 서버에서 모든 데이터가 준비될 필요가 없습니다. 화면의 일부가 최초 HTML을 보내는 작업을 지연시키면, 해당 파트를 HTML에서 제외할 것인지를 선택할 필요 없이 해당 부분만 HTML 스트리밍 상에 나중에 들어오게 할 수 있습니다. 어디에 로딩 스피너가 나타날지 정해주면, 리액트가 해당 위치에 Stram으로 script와 함께 컴포넌트를 넣어주기 때문에 데이터가 특별한 순서에 맞춰서 로딩될 필요도 없습니다.</p><h4>Hydrating the page before all the code has loaded</h4><p>React 18에서 Suspense는 댓글 위젯이 로드되기 전에 애플리케이션을 Hydration 할 수 있게 해줍니다. 유저의 관점에서 최초에는 HTML로 스트리밍된 상호작용할 수 없는 콘텐츠를 보게 됩니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*r2kS1ex5NAyppfXu.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*q_MX0iGx5llKfjBF.png" /></figure><p>이제 리액트는 Hydration을 수행하고, 이때 아직 댓글에 해당하는 코드는 로드되지 않았지만, 리액트는 Selective Hydration을 통해 댓글에 해당하는 코드를 제외하고 Hydration을 수행할 수 있습니다. (Suspense로 감싸져 있기 때문에 그렇습니다.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xDmTEnBe85PdlTfx.png" /></figure><p>Comments를 Suspense로 묶음으로써 리액트가 Streaming과 Hydration이 렌더링을 Block 하는 것을 막아줍니다. 이로 인해 “두 번째 문제(You have to load everything before you can hydrate anything)”를 해결할 수 있습니다. Hydration을 시작하기 위해 모든 코드가 로드되는 것을 기다릴 필요가 없으며 리액트 코드의 부분부분이 로드될 때마다 Hydration을 진행할 수 있습니다. 리액트는 댓글 섹션 코드가 모두 로드된 뒤에 “이 부분만” Hydration을 시작하게 됩니다. Selective-Hydration 덕분에 무거운 자바스크립트 코드의 일부가 나머지 페이지의 상호작용을 막지 않게 됩니다.</p><h4>Hydrating the page before all the HTML has been streamed</h4><p>리액트가 가장 중요하게 생각하는 “선언적(Declarative)”인 속성은 Suspense와 Hydration에도 적용됩니다. 즉, Suspense와 non-blocking Hydration에 대한 것을 리액트에서 알아서 처리한다는 것입니다. 이로 인해 작업이 예상하지 못한 순서로 진행되는 것에 대해 걱정할 필요가 없습니다. HTML을 스트리밍하는 것 자체도 여러 상황들로 인해 시간이 지연될 수 있는데, 만약 Straming HTML보다도 나머지 부분의 자바스크립트 코드가 더 빨리 로드되었다면 리액트는 나머지 페이지를 먼저 Hydration 합니다. Straming HTML이 먼저 도착하든, 자바스크립트 코드가 먼저 도착하든 Suspense는 일관적으로 non-blocking 하게 동작하며 리액트는 그저 먼저 도착한 것을 먼저 처리할 뿐입니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*J-zNSB5kogeAuhhM.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*shpPq7uCwmoi8Wa1.png" /></figure><p>위의 과정 이후 HTML이 도착하면 해당 부분만 상호작용이 불가능한 상태로 그려지고, 이후 자바스크립트가 로드되면 해당 부분까지도 상호작용이 가능한 상태로 바뀌게 됩니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*U88ilAyeCE7UygWX.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ziDbNFEqQAL75ro0.png" /></figure><h4>Interactive with the page before all the components have hydrated</h4><p>댓글 부분을 Suspense로 감쌌을 때, 드러나지 않는 개선점이 하나 더 있습니다. 즉, Hydration 과정 자체가 더 이상 브라우저를 “완전히” 점유하지 않는다는 것을 의미합니다. 예를 들어, 댓글 부분의 Hydration이 진행되는 동안 유저가 사이드바를 클릭했다고 가정해보겠습니다. React 18의 Suspense boundary 내부에서 발생하는 Hydration 과정에는 브라우저가 이벤트를 핸들링할 수 있도록 작은 여지(tiny gaps)들이 포함됩니다. (여기서는 tiny-gaps라고 다소 추상적으로 묘사했지만, Hydration 자체가 Fiber의 Rendering Phase에서 특정 우선순위를 가진 상태로 Concurrent하게 일어나기 때문에 Mouse Click, Input과 같은 더 중요한 이벤트가 발생했을 때, 이를 먼저 처리하는 여지를 준 것으로 해석할 수 있습니다.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*95VrvqNFV5oiGb24KttJjg.png" /></figure><p>이 방법을 통해 클릭은 즉시(immediatly) 처리되고 브라우저는 저사양 디바이스에서 발생하는 긴 Hydration 구간에 갇히지 않아도 됩니다. 예를 들어, 유저는 이제 더 이상 보고 싶지 않은 페이지에서 Hydration이 진행되는 동안에도 네이게이션 바를 통해 다른 페이지로 이동할 수 있게 됩니다.</p><p>앞선 예제에서 Suspense를 댓글 컴포넌트에서만 사용했지만, 아래와 같이 더 많은 위치에 배치함으로써, 나머지 구성 요소들에 대한 Hydration 작업도 분리할 수 있습니다. 예를 들어 사이드바에도 Suspense를 적용해볼 수 있습니다.</p><pre>&lt;Layout&gt;<br>  &lt;NavBar /&gt;<br>  &lt;Suspense fallback={&lt;Spinner /&gt;}&gt;<br>    &lt;Sidebar /&gt;<br>  &lt;/Suspense&gt;<br>  &lt;RightPane&gt;<br>    &lt;Post /&gt;<br>    &lt;Suspense fallback={&lt;Spinner /&gt;}&gt;<br>      &lt;Comments /&gt;<br>    &lt;/Suspense&gt;<br>  &lt;/RightPane&gt;<br>&lt;/Layout&gt;</pre><p>이제 네비게이션과 포스트를 가지고 있는 최초의 HTML이 전송된 뒤에도 서버로부터 사이드바와 댓글 컴포넌트가 스트리밍될 수 있습니다. 그리고 이 경우에는 Hydration에도 영향을 줍니다. 예를 들어 두 항목의 HTML이 모두 로드되었지만 아직 코드는 로드되지 않은 경우, 아래와 같이 보일 것입니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3-365TZ0aDrDfADK.png" /></figure><p>이 상황에서 사이드바와 댓글 코드를 가지고 있는 번들이 로드되면, 리액트는 이 둘 모두를 Hydration 하는데, 트리 상에서 더 먼저 발견되는 Suspense boundary의 컴포넌트부터 시작합니다. (이 경우 Sidbar가 해당될 것입니다.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DzQ2G62NcHBLaquZ.png" /></figure><p>이렇게 Hydration이 진행되고 있는 상황에서 유저가 댓글 쪽을 먼저 클릭하는 경우를 가정해보겠습니다. 리액트는 이러한 경우에 대해 해당 클릭을 기록하고, 이것이 더 급하기 때문에 댓글에 대한 Hydration에 우선순위를 부여합니다. 댓글 코드가 Hydration을 마치면 리액트는 기록된 클릭 이벤트를 먼저 실행하고, 다시 사이드바를 Hydration하기 시작할 것입니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DVTiXsqi6L_Mxlsu.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dcjL1PPiwuFe6R0n.png" /></figure><p>이 과정은 우리의 “세 번째 문제(You have to hydrate everything before you can interact with anything)”를 해결합니다. Selective-Hydration 덕분에, 리액트는 최대한 빨리 모든 것을 Hydration 하면서 유저의 상호작용을 기반으로 화면 상에서 가장 급한 부분에 우선순위를 부여하게 될 것입니다. Selective Hydration의 장점은 애플리케이션에 Suspense를 적용하고, 각각의 영역이 더 작아지게 되면 더 명확해질 것입니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vTRscGTsBgTbP0B5.png" /></figure><p>위 예제에서 유저는 Hydration이 시작된 후 첫 번째 댓글을 클릭합니다. 리액트는 모든 부모 Suspense 영역에 대한 Hydration을 우선시하지만, 관련 없는 sibiling 컴포넌트에 대한 Hydration은 우선 skip 할 것입니다. 이 방법은 마치 Hydration이 “즉각적으로” 이루어진다는 착각을 불러오는데, 이는 상호작용에 해당하는 컴포넌트가 가장 먼저 Hydration되기 때문입니다.</p><h3>Conclusion</h3><p>React 18이 등장하기 전까지 Suspense는 그저 “로딩 UI를 조금 더 예쁘게 보여주는 방식” 정도로 여겨졌던 것 같습니다. 하지만 브라우저를 점유하지 않고 작업을 Concurrent하게 끊어서 처리할 수 있는 기반인 Fiber Architecture, 여러 Task들 중 더 높은 우선순위가 높은 작업들을 우선 처리할 수 있게 만드는 Lane Model, 그리고 SSR에서 조금 더 우선순위가 높은 작업들을 먼저 Hydration할 수 있도록 도와주는 Suspense를 이어 붙여보니 Concurrency를 지원하기 위해 거의 모든 것을 “다시” 만들어야 했던 React 18이 새삼 대단하게 느껴지는 것 같습니다.</p><p>이러한 과정을 지원하면서도 여전히 리액트는 이 과정을 “선언적”으로 사용할 수 있게 만들어서 리액트 개발자들이 이러한 Background를 다 이해하지 못해도 이를 편하게 사용할 수 있도록 만들어주었고, 이러한 부분들이 React를 Modern Frontend Scene을 움직이는 핵심 라이브러리로 만들어주는 게 아닐까 하는 생각이 듭니다.</p><h3>Reference</h3><p><a href="https://github.com/reactwg/react-18/discussions/37">https://github.com/reactwg/react-18/discussions/37</a></p><p><a href="https://github.com/reactwg/react-18/discussions/37">New Suspense SSR Architecture in React 18 · Discussion #37 · reactwg/react-18</a></p><p><a href="https://github.com/reactwg/react-18/discussions/37">Overview React 18 will include architectural improvements to React server-side rendering (SSR) performance. These improvements are substantial and are the culmination of several years of work. Most…</a></p><p><a href="https://github.com/reactwg/react-18/discussions/37">github.com</a></p><p><a href="https://dev.to/tigt/the-weirdly-obscure-art-of-streamed-html-4gc2">https://dev.to/tigt/the-weirdly-obscure-art-of-streamed-html-4gc2</a></p><p><a href="https://dev.to/tigt/the-weirdly-obscure-art-of-streamed-html-4gc2">The weirdly obscure art of Streamed HTML</a></p><p><a href="https://dev.to/tigt/the-weirdly-obscure-art-of-streamed-html-4gc2">Literally “one weird trick” to massively improve Time To First Byte</a></p><p><a href="https://dev.to/tigt/the-weirdly-obscure-art-of-streamed-html-4gc2">dev.to</a></p><ul><li>🌏글로벌 Top 교육 앱 QANDA(콴다)를 함께 만들어 갈 Frontend개발자들을 기다리고 있습니다!</li><li>🖥️콴다 팀의 개발 문화가 궁금하다면? ➡️ <a href="https://www.youtube.com/watch?v=9Xtm92NAU58">Inside QANDA: 최고의 글로벌 교육 서비스를 개발한다는 것</a></li><li>🕹️콴다 Frontend Team은 채용 중 입니다!➡️ <a href="http://bit.ly/3pVjlmR">공고 확인하기</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec75e80eb68d" width="1" height="1" alt=""><hr><p><a href="https://blog.mathpresso.com/suspense-ssr-architecture-in-react-18-ec75e80eb68d">Suspense SSR Architecture in React 18</a> was originally published in <a href="https://blog.mathpresso.com/">Team QANDA</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Algebraic Effects of React Suspense]]></title>
            <link>https://blog.mathpresso.com/algebraic-effects-of-react-suspense-157b49807ea0?source=rss-9ce465f93d9e------2</link>
            <guid isPermaLink="false">https://medium.com/p/157b49807ea0</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[product]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[febe]]></category>
            <dc:creator><![CDATA[Yeoul]]></dc:creator>
            <pubDate>Thu, 15 Sep 2022 02:15:56 GMT</pubDate>
            <atom:updated>2023-03-19T12:03:27.199Z</atom:updated>
            <content:encoded><![CDATA[<h4>Suspense Based on Algebraic Effects</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PcwA1BwPru_Vp7Tod8-lZA.png" /></figure><h3>Overview</h3><p>React Suspense의 개념적 모델을 다룬 <a href="https://yeoulcoding.medium.com/conceptual-model-of-react-suspense-a7454273f82e">이전 포스팅</a>의 마지막 부분에서 Dan Abramov(React Core Team)의 Suspense에 대한 Comment를 잠깐 언급했습니다. 이 Comment에 대한 구체적인 내용은 아래 인용문과 같습니다.</p><p>(아래 인용문은 Suspense가 Fallback UI를 처리하기 위해서 throw 된 Promise를 사용한다는 내용을 이해하고 있다는 것을 전제로 합니다. 해당 내용에 대한 이해가 필요하다면 이에 대해 다룬 <a href="https://yeoulcoding.medium.com/conceptual-model-of-react-suspense-a7454273f82e">이전 포스팅</a>을 참고해 주세요)</p><blockquote><em>This builds on a React feature called “</em><strong><em>Suspense</em></strong><em>”, which is in active development for the data fetching use case. The interesting part, of course, is that the data might not yet be in the movieCache — in which case we need to do something because we can’t proceed below. Technically, in that case the read() call throws a Promise (yes, throws a Promise — let that sink in). </em><strong><em>This “suspends” the execution. React catches that Promise, and remembers to retry rendering the component tree after the thrown Promise resolves.</em></strong></blockquote><blockquote><strong>This isn’t an algebraic effect per se, even though this trick was inspired by them.</strong><em><br>- Dan Abramov(</em><a href="https://overreacted.io/algebraic-effects-for-the-rest-of-us/"><em>overreacted.io</em></a><em>)</em></blockquote><p>이는 Suspense가 사용하는 개념적인 모델, 즉 Data의 상태를 확인하면서 ‘<em>pending</em>’ 상태인 경우에는 원하는 데이터의 요청에 대한 promise를 throw해서 Suspense가 Fallback UI를 렌더 하도록 하고, ‘<em>success</em>’ 상태인 경우에는 Component를 렌더하도록 하는 이 모델은 <strong><em>그 자체로는 “Algebraic Effect(대수적 효과)”는 아니지만, 이로부터 영향을 받았다는 의미</em></strong>로 해석할 수 있습니다.</p><p>그렇다면 여기서의 대수적 효과라는 것이 어떤 의미이며, Suspense의 개념적 모델이 어떤 측면에서 이 대수적 효과에 영향을 받았다는 것일까요? 이번 포스팅에서는 이 부분에 대해 간략하게 살펴보도록 하겠습니다.</p><blockquote>콴다 프론트엔드 팀에서는 대부분의 웹 프로젝트와 웹뷰 프로젝트를 ReactJs + Typescript의 기술 스택(SEO대응, 저사양 디바이스에서의 성능 개선등을 위해 서버사이드 렌더링이 필요한 프로젝트의 경우에는 +NextJs)으로 개발하고 있기 때문에 React(이하 리액트)의 동작 원리에 대해서 많은 관심을 가지고 정리하고 공유하는 것을 중요하게 생각하고 있습니다.</blockquote><h3>What is Algebraic Effects?</h3><blockquote><em>algebra: a generalization of arithmetic in </em><strong><em>which letters representing numbers are combined</em></strong><em> according to the rules of arithmetic — webster dictionary</em></blockquote><p><em>“대수적 효과(Algebraic Effects)</em>”에 대해 살펴보기 위해서는 먼저 “대수”가 무엇인지에 대해 살펴보는 것이 좋을 것 같습니다. “대수(代數)”라는 말은 <em>대신할 대(代)</em> 자를 사용하는 데서 그 의미를 예측할 수 있듯이, “<em>수를 대신한다(letters representing numbers)”는</em> 뜻을 가지고 있습니다.</p><p>어떠한 수학적인 문제를 해결할 때, 수들의 연산으로 이를 해결하는 것이 아닌 문자와 문자들 사이의 추상적 관계(함수)들을 통해 이를 해결하는 방식을 ‘대수적 방식’이라고 하고, 이는 변수와 함수를 사용해서 문제를 해결하는 프로그래밍과도 관련이 있습니다.</p><p>그렇다면 대수적 효과는 무엇일까요? Matija Pretnar의 “<em>An Introduction to Algebraic Effects and Handlers Invited tutorial paper”에</em> 의하면 대수적 효과는 다음과 같이 정의됩니다.</p><blockquote><strong><em>Algebraic effects are an approach to computational effects based on a premise that impure behaviour arises from a set of operations</em></strong><em> such as get &amp; set for mutable store, read &amp; print for interactive input &amp; output, or raise for exceptions. This naturally gives rise to handlers not only of exceptions, but of any other effect, yielding a novel concept that, amongst others, can capture stream redirection, backtracking, co-operative multi-threading, and delimited continuations. — Matija Pretnar</em></blockquote><p>이를 그대로 해석하면, “<strong><em>대수적 효과란 exception throw등을 포함하는 연산들의 집합(set of operations)으로부터 순수하지 못한 행위(impure behavior)들이 발생할 수 있다는 전제를 바탕으로 Computational Effect에 대해 접근하는 방식이다”라는</em></strong> 뜻이 됩니다. 앞서 살펴본 “대수”의 정의로부터 미루어봤을 때, “exception throw등을 포함하는 연산들의 집합” 은 “수를 대신하는 변수(대수)를 사용하는 프로그램에서 목적을 달성하기 위한 연산들이 일어나고, 그 연산의 집합(set)의 구성요소(element)중 하나로 exception throw등이 있다”고 이해할 수 있을 것 같습니다. 즉 대수적 효과란 대수를 사용해서 연산을 수행할 때 순수하지 못한 행위들이 일어날 수 있고, 이를 전제로 Computational Effect에 대해 접근하는 방식이라는 것인데 “순수함수”, “Computational Effects”와 같은 용어들로 인해 이를 그대로 받아들이기에는 조금 난해한 부분이 있으므로, 먼저 이 요소들을 하나씩 쪼개서 살펴보도록 하겠습니다.</p><h4>순수(pure)한 행위와 순수하지 못한(impure) 행위</h4><p>컴퓨터 프로그래밍에서 “순수”한 것이 무엇인지를 알기 위해서 순수 함수의 정의를 먼저 살펴볼 필요가 있습니다. 아래의 정의에 따르면 어떤 함수가 순수하다는 것은, <em>동일한 입력에 대해 항상 동일한 결과를 리턴하고, Side Effect를 발생시키지 않는 것</em>을 의미합니다. 이 정의 하에서 exception throw와 같은 연산은 Side Effect를 발생시키며, 따라서 비순수한 행위라고 할 수 있습니다.</p><blockquote><em>In </em><a href="https://en.wikipedia.org/wiki/Computer_programming"><em>computer programming</em></a><em>, a pure function is a </em><a href="https://en.wikipedia.org/wiki/Subroutine"><em>function</em></a><em> that has the following properties:</em></blockquote><blockquote><em>1. the function return values are identical for identical arguments (no variation with local static variables, non-local variables, mutable reference arguments or input streams)</em></blockquote><blockquote><em>2. the function application has no side effects (no mutation of local static variables, non-local variables, mutable reference arguments or input/output streams).</em></blockquote><h4>Computational Effect</h4><p>Computational Effect라는 용어를 “컴퓨터 효과”라고 번역하는 것이 정확하지 않은 느낌이 들어서, 이 글에서는 해당 단어를 번역하지 않고 원문 그대로 사용하겠습니다. 아래는 Stackoverflow에서 Computational Effect를 잘 정의한 글이 있어서 이를 인용한 것입니다.</p><blockquote><em>An computational effect is </em><strong><em>any computation that includes an alteration of its environment</em></strong><em>. For example, things like total disk capacity, network connectivity are external effects, that play a role in operations like reading/writing files or accessing a database. Anything that a function produces, besides the value it computes, is a computational effect. From the perspective of that function, even another function that accesses the same memory as that function does, can be considered an effect.</em></blockquote><blockquote><em>That’s the theoretical definition. </em><strong><em>Practically, its useful to think of an effect as any interaction between a sub expression and a central control which handles global resources in a program</em></strong><em>. Sometimes, a local expression may need to send messages to the central control while execution, along with enough information so that once the central control is done, it can resume the suspended execution. — </em><a href="https://stackoverflow.com/questions/49626714/what-does-algebraic-effects-mean-in-fp"><em>stackoverflow</em></a></blockquote><p>인용한 글에 의하면 Computational Effect는 “<em>자신의 환경(environment)을 변경하는 모든 연산</em>”을 포함하는 개념입니다. 이는 이론적인 관점에 가까우므로 조금 더 실용적인 관점에서 설명한다면, <strong><em>“sub-expression”과 “central-control” 사이에서 일어나는 interaction을 의미합니다.</em></strong> (서로 다른 환경이라는 것이 중요하므로 여기서는 굳이 central, sub와 같은 용어에 집중할 필요는 없습니다.)</p><p>예를 들어, 어떤 로컬 함수(sub-expression)에서 부모 환경(central-control)으로 어떤 작업을 넘겨 처리하게 하고, 처리가 끝나면, 다시 로컬 함수의 실행이 멈췄던 곳으로 돌아가 작업을 계속한다면, 여기에서는 Computational Effect가 발생한 것입니다.</p><p>(작업을 넘긴다는 것을 부모 컴포넌트로 promise를 throw하는 것으로 바꿔서 생각해보면 이것이 바로 Suspense가 Fallback UI를 처리하는 방식이라는 것을 알아차릴 수 있을 것입니다.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/0*9UZQq_X-hCH-5vA9.png" /></figure><p>이를 바탕으로 위의 대수적 효과의 정의를 다시 한번 살펴보면, 다음과 같이 이해할 수 있을 것입니다.</p><p><strong><em>“대수적 효과(Algebraic Effects)란 서로 다른 환경 사이의 interaction에서 발생하는 Computational Effects에 대한 접근 방식을 의미한다. 여기에는 전제가 있는데, 이러한 Computational Effects로부터 순수하지 못한 효과가 발생한다는 것이다.</em></strong>”</p><p>훨씬 나아졌습니다. 그렇다면 이 대수적 효과의 접근 방식이라는 것이 무엇일까요? 앞서 인용한 논문의 바로 다음 문장에 의하면, 이는 <strong><em>적절한 “handler”를 사용하는 것을 의미</em></strong>합니다.</p><blockquote><em>This naturally gives rise to handlers not only of exceptions, but of any other effect, yielding a novel concept that, amongst others, can capture stream redirection, backtracking, co-operative multi-threading, and delimited continuations</em></blockquote><p>즉 Algebraic Effect는 서로 다른 환경 사이의 interaction에서 impure 한 SideEffect가 발생할 수 있는데, 이것을 적절한 handler를 사용해 해결하는 접근 방식을 의미하는 것이고, 이 handler는 “sub-expression”에서 발생시킨 effect를 “central-control”에서 잡아 적절하게 처리한 뒤, 다시 “sub-expression”이 멈췄던 곳으로 흐름을 되돌려 주는 것입니다.</p><h3>Why does it matters? (with Suspense)</h3><blockquote><em>Try to think of Algebraic Effects as some sort of try / catch mechanism, </em><strong>where the catch handler does not just “handle the exception”, but is able to provide some input to the function which threw the exception</strong><em>. The input from the catch handler is then used in the throwing function, which continues as if there was no exception. — </em><a href="https://stackoverflow.com/a/57280373"><em>stackoverflow</em></a></blockquote><p>지금까지 꽤나 긴 호흡으로 대수적 효과(Algebraic Effect)가 무엇인지에 대해 살펴보았습니다. 그렇다면, 왜 이것이 React를 이해하는데에 중요하며, Suspense에 영향을 미치게 된 것일까요? 이를 살펴보기 위해 이미 여러 번 다른 문장으로 살펴보았던 Algebraic Effect를 <em>조금 더 Javascript적이고 React적인 관점을 담아</em> 소개해 보도록 하겠습니다.</p><p>참고로, 이 문장은 100% 정확한 Algebraic Effect를 나타내지는 않을 수 있습니다.(제가 임의로 이해하기 쉽게 작성한 것입니다.) Dan Abramov 자신도 React Suspense에 적용된 개념적 모델이 정확히 Algebraic Effect는 아니며, 여기서 영감을 얻었다고 했기 때문에 개념에 대한 인사이트를 얻는다면 그것으로 충분할 것입니다. <em>(This isn’t an algebraic effect per se, even though this trick was inspired by them. — Dan)</em></p><blockquote>“Algebraic Effect는 부모 컴포넌트(<strong>Suspense</strong>)와 자식 컴포넌트(<strong>UserList</strong>) 사이의 interaction에서 발생한 SideEffect(<strong>throw Promise</strong>)를 적절한 Handler(<strong>catch Promise in Suspense</strong>)를 사용해 해결하는 접근 방식을 의미하는 것이고, 이 Handler는 sub-expression(<strong>UserList</strong>)에서 발생시킨 Effect(<strong>throw Promise</strong>)를 central-control(<strong>Suspense</strong>)에서 잡아 적절하게 처리한 뒤, 다시 sub-expression(<strong>UserList</strong>)이 멈췄던 곳으로 흐름을 되돌려 주는 것입니다.”</blockquote><p>Algebraic Effects와 Suspense와의 연관성이 보이시나요? 이렇게 Algebraic Effects는 어떤 코드 조각을 감싸는 맥락으로 순수하지 못한 동작에 대한 책임을 분리하고, 분리된 책임에 대한 처리는 감싸는 맥락에서 처리하게 함으로써 “무엇”과 “어떻게”를 분리합니다. 이렇게 책임을 분리하는 방식은 코드를 조금 더 “선언적”으로 작성할 수 있는 관점을 제공하며, 이것은 React가 지향하는 것과 완전히 동일합니다..(더 자세한 내용은 <a href="https://blog.mathpresso.com/declarative-react-and-inversion-of-control-7b95f3fbddf5">선언형 UI 라이브러리로서의 React를 다룬 이전 포스팅</a>을 참고해 주세요.)</p><p>Suspense는 Algebraic Effects를 사용해서 부모 컴포넌트에게 로딩 상태에 대한 처리의 “책임”을 넘겼으며, 따라서 메인 컴포넌트에서 로딩 UI 표시의 책임을 “분리”하게 됩니다. 이는 UI Component를 조금 더 “선언적”으로 작성하도록 만들어주며, 이것은 React가 지향하는 바입니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/0*IbEXQ5mTuFMKYKYC.png" /></figure><h3>Conclusion</h3><p>Algebraic Effects는 아직 특정한 프로그래밍 언어에 구현되어 널리 사용되고 있는 상용화된 패러다임은 아닙니다. (적어도 Javascript에서는 Algebraic Effects를 지원하지 않습니다.) 하지만 이것이 제공하는 Basic Idea는 React의 선언적인 속성과 IoC(Inversion of Control)에 많은 영향을 주었으며, Suspense도 그 영향을 받은 Component라고 이야기할 수 있습니다.</p><p>가볍게 시작했다가, 꽤나 많은 내용을 다루게 된 글인 것 같습니다. 다음 포스팅에서는 실제로 이 Suspense가 내부적으로 어떻게 구현되어 있는지를 두 차례에 걸쳐서 살펴보려고 합니다.</p><h3>Reference</h3><p><a href="https://overreacted.io/algebraic-effects-for-the-rest-of-us/">https://overreacted.io/algebraic-effects-for-the-rest-of-us/</a></p><p><a href="https://www.sciencedirect.com/science/article/pii/S1571066115000705?ref=pdf_download&amp;fr=RR-2&amp;rr=749811e798baa7d2">An Introduction to Algebraic Effects and Handlers</a></p><p><a href="https://arxiv.org/pdf/1203.1539.pdf">Programming with Algebraic Effects and Handlers</a></p><p><a href="https://stackoverflow.com/questions/49626714/what-does-algebraic-effects-mean-in-fp">What does algebraic effects mean in FP?</a></p><ul><li>🌏글로벌 Top 교육 앱 QANDA(콴다)를 함께 만들어 갈 Frontend개발자들을 기다리고 있습니다!</li><li>🖥️콴다 팀의 개발 문화가 궁금하다면? ➡️ <a href="https://www.youtube.com/watch?v=9Xtm92NAU58">Inside QANDA: 최고의 글로벌 교육 서비스를 개발한다는 것</a></li><li>🕹️콴다 Frontend Team은 채용 중 입니다!➡️ <a href="http://bit.ly/3pVjlmR">공고 확인하기</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=157b49807ea0" width="1" height="1" alt=""><hr><p><a href="https://blog.mathpresso.com/algebraic-effects-of-react-suspense-157b49807ea0">Algebraic Effects of React Suspense</a> was originally published in <a href="https://blog.mathpresso.com/">Team QANDA</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Conceptual Model of React Suspense]]></title>
            <link>https://blog.mathpresso.com/conceptual-model-of-react-suspense-a7454273f82e?source=rss-9ce465f93d9e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7454273f82e</guid>
            <category><![CDATA[web]]></category>
            <category><![CDATA[suspense]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[febe]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Yeoul]]></dc:creator>
            <pubDate>Thu, 15 Sep 2022 02:03:34 GMT</pubDate>
            <atom:updated>2023-03-26T12:54:07.291Z</atom:updated>
            <content:encoded><![CDATA[<h4>Suspense with Concurrent React</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9FTIYnCEPsh4Ae5Mlf3Bng.png" /></figure><h3>Overview</h3><p><a href="https://reactjs.org/blog/2022/03/29/react-v18.html">React v18의 정식 릴리즈</a>가 나오면서 Automatic Batching, Transition등 여러 Feature들이 소개되었습니다. 그중에는 React v16.6에 Experimental Feature로 등장했다가 이번에 정식으로 탑재된 “<em>Suspense</em>”에 대한 내용도 추가되어 있는데, 이번 포스팅에서는 특별히 이 Suspense라는 기능에 대해서 살펴보려고 합니다.</p><blockquote><em>콴다 프론트엔드 팀에서는 대부분의 웹 프로젝트와 웹뷰 프로젝트를 ReactJs + Typescript의 기술 스택(SEO대응, 저사양 디바이스에서의 성능 개선등을 위해 서버사이드 렌더링이 필요한 프로젝트의 경우에는 +NextJs)으로 개발하고 있기 때문에 React의 동작 원리에 대해서 많은 관심을 가지고 정리하고 공유하는 것을 중요하게 생각하고 있습니다.</em></blockquote><h3>What is Suspense?</h3><blockquote><em>Suspense </em><strong><em>lets your components “wait” for something before they can render</em></strong><em>. In this example, two components wait for an asynchronous API call to fetch some data: — </em><a href="https://17.reactjs.org/docs/concurrent-mode-suspense.html#what-is-suspense-exactly"><em>React Official Docs</em></a></blockquote><p>Suspense는 컴포넌트의 렌더링을 어떤 작업이 끝날 때까지 잠시 중단시키고, 다른 컴포넌트를 먼저 렌더링 할 수 있도록 도와주는 기능입니다. Suspense를 사용하면 Component Lazy Loading이나 Data Fetching 등의 비동기 처리를 할 때, 응답을 기다리는 동안 fallback UI(<em>e.g Spinner</em>)를 보여주고, 그 사이에 우선순위가 높은 다른 UI들을 먼저 렌더링 할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hFw8tAl9tSnZcz8M.png" /><figcaption>suspense를 사용한 예시</figcaption></figure><p>React 공식문서에 따르면, 현재(v18) Suspense는 공식적으로 <em>React.lazy를 사용한Lazy Loading Component </em>를 기다릴 때 사용하고, Data Fetching에 사용되는 것이 가능은 하지만 아직까지 권장되지는 않는다고 이야기하고 있습니다. 하지만 이번 포스팅에서는 Suspense를 Data Fetching에 사용하는 경우에 대해서 집중적으로 살펴볼 텐데, 이는 React Core Team이 궁극적으로 <strong><em>Suspense를 Data Fetching 뿐 아니라 이미지 로딩 등 어떠한 형태의 “비동기 요청”에 대해서도 사용할 것이라는 목표를</em></strong> 가지고 있기 때문입니다.</p><p>(<em>실제로 모든 라이브러리들은 아니지만 </em><a href="https://relay.dev/docs/guided-tour/rendering/loading-states/"><em>Relay</em></a><em>, </em><a href="https://swr.vercel.app/docs/suspense"><em>SWR</em></a><em>, </em><a href="https://recoiljs.org/docs/guides/asynchronous-data-queries/#asynchronous-example"><em>Recoil</em></a><em>와 같은 Library에서는 이미 Suspense를 사용해서 Data Fetching을 할 수 있도록 지원하고 있으며, 앞으로 대부분의 Data Fetching Library들이 Suspense에 대한 지원을 추가하게 될 것입니다.</em>)</p><p>이어지는 문단들에서도 계속 언급하겠지만, Suspense는 React 18의 핵심 기능 중 하나인 Concurrency(동시성)과 깊은 관련이 있으며, 선언형 UI 라이브러리로서의 React가 에러 / 비동기 / 정상 상태를 조금 더 “<em>선언적(Declarative)</em>”으로 표현할 수 있도록 하는데 도움을 줍니다.</p><blockquote><em>As in previous versions of React, you can also use Suspense for code splitting on the client with React.lazy. But our vision for Suspense has always been about much more than loading code — </em><strong><em>the goal is to extend support for Suspense so that eventually, the same declarative Suspense fallback can handle any asynchronous operation (loading code, data, images, etc). — </em></strong><a href="https://reactjs.org/blog/2022/03/29/react-v18.html"><strong><em>React Official Docs</em></strong></a></blockquote><h3>Suspense Official Example (from React Team)</h3><p>React 공식문서에서 제공한 아래의 예시[<a href="https://codesandbox.io/s/festive-elion-eb52b6"><strong>CodeSandbox</strong></a>]를 통해 Suspense를 Data Fetching과 함께 사용하는 방법에 대해 살펴보겠습니다. “<em>ProfilePage</em>” 안에는 “<em>ProfileDetails</em>”와 “<em>ProfileTimeline</em>”이라는 2개의 컴포넌트가 있고, 각 컴포넌트는 비동기 데이터를 가져와 화면에 렌더링 하게 되며, 비동기 데이터를 가져오는 동안 보여줄 FallbackUI를 컴포넌트를 감싼 Suspense에 넣어주었습니다.</p><p>(유저에게 보여주는 데이터를 가져오기 위해서 조금은 생소한 <em>resource.user.read()</em> 와 같은 문법을 사용했는데, 이 부분에 대해서는 아래 섹션에서 설명할 예정이니 지금은 해당 문법이 “<em>fetchData()</em>” 정도의 역할을 수행한다고 이해하고 넘어가는 것이 좋습니다.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/0*PlAjLNHHJurTVuT3.png" /></figure><p>아래는 위의 예제를 실행한 결과입니다. user를 가져오는 API에는 1000ms의 딜레이를 주었고, post를 가져오는 API에는 1100ms의 딜레이를 주었습니다. 여기서 주목할 만한 점은 UserData가 도착한 뒤에 또 다른 1100ms를 기다렸다가 PostData가 로드되는 것이 아니라 <strong><em>UserData와 PostData가 동시에(정확하게는 Concurrent 하게) 요청되고 이에 따라 1100ms 안에 모든 데이터가 로드되어 모든 화면이 나타나게 된다는 것입니다.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*JekNHA8rO9wwgNFR.gif" /></figure><h3>What Problem Does it Solve?</h3><p>React Core Team이 Suspense를 React 18의 Official Feature로 소개하고, 궁극적으로 Data Fetching이나 Image Loading과 같은 모든 비동기 요청을 처리하도록 만들 것이라고 한 이유는 <strong><em>Suspense가 기존에 비동기 요청을 처리하는데에서 발생하는 여러 문제들을 해결한다고 판단</em></strong><em>했기 때문 </em>일 것입니다. 그렇다면 React Core Team에서는 Suspense를 사용해서 어떤 문제를 해결하려고 한 것일까요?</p><h4>Declarative React</h4><p>Suspense를 사용하기 전, React에서 비동기 데이터를 처리하는 과정을 살펴보면 <strong><em>하나의 컴포넌트 안에서 꽤나 많은 분기를 가지고 있음</em></strong>을 알 수 있습니다. 아래 왼쪽의 예시에서도 이러한 분기가 드러나는데, 데이터를 가져오는 부분, loading을 처리하는 부분, 그리고 필요에 따라 error를 처리하는 부분까지 모두 하나의 컴포넌트에서 처리하고 있습니다. 이러한 분기를 생성하는 책임은 개발자에게 있었으며, 개발자는 코드를 작성해서 데이터가 로딩 중인지, 에러가 발생했는지, 정상적으로 로딩되었는지를 다소 “명령적(Imperative)”인 방법으로 확인해야 했습니다.</p><p>하지만, 오른쪽 예시와 같이 Suspense를 사용하면, <strong><em>로딩을 처리하는 부분에 대한 책임과 데이터가 로딩되었는지를 판단하는 책임을 Suspense에 맡기고</em></strong>, 컴포넌트는 정상적으로 데이터가 로딩되었을 때의 UI만 “선언”할 수 있게 됩니다.</p><p>이때, React의 <a href="https://reactjs.org/docs/error-boundaries.html">ErrorBoundary</a>를 같이 사용하면, “<strong><em>정상 / 로딩 중 / 에러 발생 </em></strong>“의 3가지 상태를 분리해서 선언할 수 있게 됩니다. 즉, Suspense를 사용함으로써 개발자는 데이터의 로딩 여부를 판단하고 로딩 중일 때의 UI를 보여주는 책임을 Suspense에게 위임하고, 원래 보여야 하는 UI(정상 상태)를 로딩 중 / 에러 발생과 같은 상태와 분리해서 생각할 수 있게 합니다. 그리고 이는 개발자로 하여금 비즈니스 로직과 UI에 조금 더 집중할 수 있도록 도와줍니다. (선언형 UI 라이브러리로써의 React에 대한 내용은 <a href="https://blog.mathpresso.com/declarative-react-and-inversion-of-control-7b95f3fbddf5">이 글</a>을 참고해주세요)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/0*xS3zJ5ZAtFIDyfEJ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/0*oa-MKxky2N8yU51d.png" /><figcaption>Without Suspense(left) — With Suspense(right)</figcaption></figure><h4>Concurrent React (fix Waterfall Rendering)</h4><p>앞선 React 공식 문서의 예시에서 두 번의 API요청(각각 1000ms, 1100ms가 소요됩니다)이 모두 Resolve 되어 화면에 데이터가 나타날 때까지 걸린 시간은 대략 “<em>1100ms + a”입니다.</em></p><p>같은 레이아웃을 Suspense를 사용하지 않고 요청하게 되면(위의 왼쪽 예제 참고), 1000ms 요청이 Resolve 된 후, loading 상태가 변경되어야지만 Child Component가 렌더 되고, 해당 컴포넌트가 렌더 되기 시작한 후에야 두 번째 요청(1100ms) 요청이 시작되기 때문에 동일한 화면을 그리는데 필요한 시간이 “<em>2100ms + a”가</em> 됩니다.</p><p>당연히 Suspense를 사용한 첫 번째 케이스가 더 나은 사용자 경험을 제공하게 되며, React 공식문서에서는 이를 <strong><em>“Render-as-You-Fetch” </em></strong>라 부릅니다.</p><blockquote><em>In the previous approach, we fetched data before we called setState:<br>- Start fetching<br>- Finish fetching<br>- Start rendering</em></blockquote><blockquote><strong><em>With Suspense, we still start fetching first, but we flip the last two steps around:</em></strong><em><br></em><strong><em>- Start fetching</em></strong><em><br></em><strong><em>- Start rendering</em></strong><em><br></em><strong><em>- Finish fetching</em></strong></blockquote><blockquote><em>With Suspense, we don’t wait for the response to come back before we start rendering. In fact, we start rendering pretty much immediately after kicking off the network request — </em><a href="https://17.reactjs.org/docs/concurrent-mode-suspense.html#approach-3-render-as-you-fetch-using-suspense"><em>React Official Docs</em></a></blockquote><p>즉, 아직 <em>데이터 로딩이 완료되지 않아 Fallback UI를 보여주게 되더라도, React는 ‘hidden’ 모드로 Child Component를 렌더 </em>하게 되며, 이로 인해 아직 부모 컴포넌트가 로딩 중이더라도 자식 컴포넌트는 자신의 Data Fetching을 Concurrent 하게 수행할 수 있게 되는 것입니다.</p><p>아래의 코드는 실제 React Implementation 중 Suspense가 Fallback과 Children 렌더링을 위해 사용하는 로직의 일부인데, 로직을 살펴보면 해당 함수가 리턴하는 것은 “fallbackChildFragment”이지만, 실제로 <a href="http://xn--with%20suspense%2C%20we%20dont%20wait%20for%20the%20response%20to%20come%20back%20before%20we%20start%20rendering-4166e.%20in%20fact%2C%20we%20start%20rendering%20pretty%20much%20immediately%20after%20kicking%20off%20the%20network%20request/">Offscreen</a>에서 primaryChildFragment, 즉 로딩이 끝났을 때 보여줘야 하는 페이지도 “hidden” 모드로 렌더링하고 있는 것을 확인할 수 있습니다. (Suspense의 실제 Fiber 구현에 대한 Detail은 이후 DeepDive 시리즈를 통해 살펴볼 예정입니다.)</p><pre>function mountSuspenseFallbackChildren(<br>  workInProgress,<br>  primaryChildren,<br>  fallbackChildren,<br>  renderLanes,<br>) {<br>  const mode = workInProgress.mode<em>;</em><br>  const progressedPrimaryFragment: Fiber | null = workInProgress.child<em>;</em></pre><pre>  const primaryChildProps: OffscreenProps = {<br>    mode: &#39;hidden&#39;,<br>    children: primaryChildren,<br>  }<em>;</em></pre><pre>  let primaryChildFragment<em>;</em><br>  let fallbackChildFragment<em>;</em></pre><pre>  primaryChildFragment = mountWorkInProgressOffscreenFiber(<br>     primaryChildProps,<br>     mode,<br>     NoLanes,<br>  )<em>;</em><br>  fallbackChildFragment = createFiberFromFragment(<br>     fallbackChildren,<br>     mode,<br>     renderLanes,<br>     null,<br>  )<em>;</em></pre><pre>  primaryChildFragment.return = workInProgress<em>;</em><br>  fallbackChildFragment.return = workInProgress<em>;</em><br>  primaryChildFragment.sibling = fallbackChildFragment<em>;</em><br>  workInProgress.child = primaryChildFragment<em>;</em><br>  return fallbackChildFragment<em>;</em><br>}</pre><h3>How Suspense Works (Brief Concept)</h3><p>지금까지 살펴본 내용을 정리해보면, Suspense는 개발자가 Data Loading에 대한 상태를 선언적으로 관리할 수 있는 방식을 제공하며, 이로 인해 메인 컴포넌트가 “데이터가 성공적으로 로드되었을 때”에 대한 상태만 신경 쓸 수 있게 도와주는 역할을 한다는 것을 살펴보았습니다.</p><p>그렇다면, 실제로 Suspense는 어떻게 Child Component의 데이터 로딩에 대한 상태를 확인할 수 있는 것일까요? 이에 대한 React Core Team의 idea들을 살펴보도록 하겠습니다.</p><p><em>(FYI. React Core Team은 Twitter를 적극적으로 사용하는 것으로 보입니다. 이들을 Follow 해두면 유용한 Insight들을 얻을 때가 많습니다.)</em></p><p>먼저 React Core Team이자 Concurrent React를 위한 Lane Model을 개발한 “Andrew Clark”의 Suspense에 대한 트윗을 확인해보도록 하겠습니다. 여기서 그는 Suspense가 동작하는 방식을 다음과 같이 소개하고 있습니다.</p><ol><li>render method에서 캐시로부터 값을 읽기를 시도한다</li><li>value가 캐시 되어 있으면 정상적으로 렌더 한다</li><li>value가 캐시 되어 있지 않으면 캐시는 “<strong><em>Promise를 throw 한다</em></strong>”</li><li>promise가 resolve 되면, React는 “Promise를 throw 한 곳으로부터” 재시작한다.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/0*IUUefM1cB3a8rcrg.png" /></figure><p>이를 User Profile을 로드하는 위의 예제를 통해 살펴보면 다음과 같습니다.</p><ol><li>Suspense가 Child Component를 렌더 할 때, 데이터(user profile)를 캐시로부터 읽으려고 시도한다</li><li>데이터가 없으므로, ChildComponent의 “캐시(의 역할을 하는 것)”는 promise를 throw 한다.</li><li>Suspense는 이 promise를 받아 fallback을 처리하고 정상적으로 resolve 되었다면 다시 ChildComponent를 보여준다.</li></ol><p>중요한 포인트는 데이터가 로딩 중일 때, “<em>컴포넌트는 Suspense(가장 가까운 Parent에 위치한)에게 promise를 throw</em>” 한다는 것과, 데이터가 “<em>로딩되고 나면(Promise가 Resolve 되고 나면), Suspense는 Fallback UI를 보여주는 것을 멈추고, 다시 정상적으로 컴포넌트를 로딩한다 </em>“ 는 점입니다. 익숙하지 않은 내용인만큼, 이에 대한 React Core Team의 개념적 구현(실제 구현은 이보다 조금 더 복잡하며 Fiber와 Lane Model에 대한 이해가 필요합니다.)을 통해 이 과정을 다시 한번 살펴보도록 하겠습니다.</p><p>[<a href="https://gist.github.com/sebmarkbage/2c7acb6210266045050632ea611aebee">Prev React Core Team Sebastian Markbåge Example</a>] — Suspense Mechanism</p><pre><em>// Infrastructure.js</em><br>let cache = new Map();<br>let pending = new Map();</pre><pre>function fetchTextSync(url) {<br>  if (cache.has(url)) {<br>    return cache.get(url);<br>  }<br>  if (pending.has(url)) {<br>    throw pending.get(url);<br>  }<br>  let promise = fetch(url).then(<br>    response =&gt; response.text()<br>  ).then(<br>    text =&gt; {<br>      pending.delete(url);<br>      cache.set(url, text);<br>    }<br>  );<br>  pending.set(url, promise);<br>  throw promise;<br>}</pre><pre>async function runPureTask(task) {<br>  for (;;) {<br>    try {<br>      return task();<br>    } catch (x) {<br>      if (x instanceof Promise) {<br>        await x;<br>      } else {<br>        throw x;<br>      }<br>    }<br>  }<br>}</pre><p>위의 Andrew Clark가 설명한 모델의 개념적 구현입니다. fetchTextSync라는 메서드는 실제 url로부터 데이터를 fetch 하는 역할을 합니다. 이 함수의 구현을 보면, fetch 요청의 완료 여부에 따라 리턴하는 값이 다른데, 아직 로딩 중이면 아직 resolve 되지 않은 promise를 리턴하고, 값이 도착하면 promise가 resolve 되면서 Set 한 캐시의 value를 리턴합니다.</p><p>이는 Suspense의 개념적 구현에서 중요한 의미를 갖는데, <em>동일한 함수를 동일한 url을 가지고 여러 번 호출했을 때 promise의 resolve 여부에 따라서 리턴(혹은 throw)하는 값이 다르므로 이에 대한 처리가 가능하게</em> 됩니다. 즉, promise를 throw 했을 때는 Suspense에서 이를 잡아서 resolve 될 때까지 fallback UI를 보여주다가 resolve가 되면, 다시 throw 한 곳으로부터 정상적인 컴포넌트 로딩을 처리할 수 있게 되는 것입니다. (아래 runPureTask라는 함수도 이와 개념적으로 동일합니다.)</p><h3>React Official Example Recap</h3><p>지금까지 살펴본 내용을 바탕으로 위의 React 공식문서 예제를 다시 한번 보겠습니다. Suspense로 감싼 ProfileDetails 라는 컴포넌트 안에 const user = resource.user.read() 라는 메서드 호출이 보이는데, 이 메서드를 가지고 있는 resource는 fetchProfileData 라는 함수의 호출로 가져오게 됩니다.</p><p>이 fetchProfileData 라는 함수는 비동기 요청을 wrapPromise 라는 함수로 한번 감싸고, 이렇게 감싸진 user 라는 리소스는 read() 라는 메서드를 제공합니다. ProfileDetails 에서는 주기적으로 .read() 메서드를 호출해서 값을 가져오는데, 아직 비동기 요청이 resolve가 되지 않았다면 .read() 메서드는 promise를 부모 Suspense로 Throw하게 되고, resolve가 되었다면 정상적으로 화면을 로드하게 되는 것입니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/0*PlAjLNHHJurTVuT3.png" /></figure><p>fetchProfileData 와 wrapPromise 의 구현은 다음과 같습니다. (아래 주석에도 쓰여있듯, 이는 Suspense와 이를 둘러싼 Data Fetching에 대한 개념적 모델을 구현한 프로토타입이므로 실제로 React가 이렇게 Suspense와 Data Fetching을 처리하지는 않는다는 것을 주의해야 합니다.)</p><pre>export function fetchProfileData() {<br>  let userPromise = fetchUser();<br>  let postsPromise = fetchPosts();<br>  return {<br>    user: wrapPromise(userPromise),<br>    posts: wrapPromise(postsPromise)<br>  };<br>}<br><br><em>// Suspense integrations like Relay implement</em><br><em>// a contract like this to integrate with React.</em><br><em>// Real implementations can be significantly more complex.</em><br><em>// Don&#39;t copy-paste this into your project!</em><br>function wrapPromise(promise) {<br>  let status = &quot;pending&quot;;<br>  let result;<br>  let suspender = promise.then(<br>    (r) =&gt; {<br>      status = &quot;success&quot;;<br>      result = r;<br>    },<br>    (e) =&gt; {<br>      status = &quot;error&quot;;<br>      result = e;<br>    }<br>  );<br>  return {<br>    read() {<br>      if (status === &quot;pending&quot;) {<br>        throw suspender;<br>      } else if (status === &quot;error&quot;) {<br>        throw result;<br>      } else if (status === &quot;success&quot;) {<br>        return result;<br>      }<br>    }<br>  };<br>}<br><br>function fetchUser() {<br>  console.log(&quot;fetch user...&quot;);<br>  return new Promise((resolve) =&gt; {<br>    setTimeout(() =&gt; {<br>      console.log(&quot;fetched user&quot;);<br>      resolve({<br>        name: &quot;Ringo Starr&quot;<br>      });<br>    }, 1000);<br>  });<br>}<br><br>function fetchPosts() {<br>  console.log(&quot;fetch posts...&quot;);<br>  return new Promise((resolve) =&gt; {<br>    setTimeout(() =&gt; {<br>      console.log(&quot;fetched posts&quot;);<br>      resolve([<br>        {<br>          id: 0,<br>          text: &quot;I get by with a little help from my friends&quot;<br>        },<br>        {<br>          id: 1,<br>          text: &quot;I&#39;d like to be under the sea&quot;<br>        },<br>        {<br>          id: 2,<br>          text: &quot;You got that sand all over your feet&quot;<br>        }<br>      ]);<br>    }, 1100);<br>  });<br>}</pre><h3>Conclusion</h3><p>Suspense의 Basic Idea를 이해하기 위해 먼 길을 달려온 것 같습니다. 위의 내용들을 요약해서 bullet list로 정리하며 이번 포스팅을 마무리하도록 하겠습니다. 이후 포스팅에서는 이러한 Basic Idea를 가진 Suspense가 Fiber Architecture 안에서 실제로 어떻게 구현되어 있는지를 살펴보도록 하겠습니다.</p><ul><li>React Suspense는 컴포넌트가 무언가를 렌더하기 위해 “wait”할 수 있도록 도와주며, 여기서의 “wait”은 데이터 로딩을 포함한 모든 비동기 요청이 해당될 수 있다.</li><li>(Error Boundary와 함께) Suspense를 사용하면 개발자는 컴포넌트에서 사용할 데이터가 “정상적으로 로드되었을 때”의 UI만 고려하면 되고, 로딩 중이나 에러의 상태에서의 UI는 위임하면 된다. (하나의 컴포넌트에서 각각의 상태에 대한 관리를 명령적으로 관리할 필요가 없다)</li><li>Suspense는 Fallback UI를 보여주는 동안에도 Child Component를 렌더한다(단지 보이지 않을 뿐.) 따라서 보다 Concurrent하게 데이터를 요청할 수 있고, 결과적으로 그렇지 않을 때 보다 더 나은 사용자 경험을 제공한다.</li><li>Suspense가 Fallback UI를 보여주기 위해 사용하는 개념적인 방식은 “promise를 Throw하는 것이다.” promise가 throw되면 이 promise가 resolve되기 전까지 Fallback UI를 보여주고 resolve되면, hidden 상태였던 Child Component를 “보여준다”</li></ul><p>React Core Team의 Dan Abramov는 Suspense가 사용하는 이러한 방식은 “대수적 효과”에서 기인한 것이라고 이야기했습니다. 다음 포스팅에서는 이 대수적 효과가 무엇인지, Suspense가 이 대수적 효과와 어떤 연관이 있는지를 간단하게 살펴보도록 하겠습니다.</p><h3>Reference</h3><p><a href="https://github.com/reactjs/rfcs/blob/main/text/0213-suspense-in-react-18.md">https://github.com/reactjs/rfcs/blob/main/text/0213-suspense-in-react-18.md</a></p><p><a href="https://17.reactjs.org/docs/concurrent-mode-suspense.html">https://17.reactjs.org/docs/concurrent-mode-suspense.html</a></p><p><a href="https://dev.to/darkmavis1980/a-practical-example-of-suspense-in-react-18-3lln">https://dev.to/darkmavis1980/a-practical-example-of-suspense-in-react-18-3lln</a></p><p><a href="https://maxkim-j.github.io/posts/suspense-argibraic-effect">https://maxkim-j.github.io/posts/suspense-argibraic-effect</a></p><p><a href="https://overreacted.io/ko/algebraic-effects-for-the-rest-of-us/">https://overreacted.io/ko/algebraic-effects-for-the-rest-of-us/</a></p><p><a href="https://pdf.sciencedirectassets.com/272990/1-s2.0-S1571066115X00107/1-s2.0-S1571066115000705/main.pdf?X-Amz-Security-Token=IQoJb3JpZ2luX2VjEOb%2F%2F%2F%2F%2F%2F%2F%2F%2F%2FwEaCXVzLWVhc3QtMSJGMEQCIB%2B5R2ccYYcGt0RzzwjLilK%2BKMPJuvFhS2OVVeF6xJ%2BcAiBZhVTDt0aDSl6JuD1R9a9pB4wZrkNnozy0zlg97gTuAirMBAh%2BEAUaDDA1OTAwMzU0Njg2NSIM2VPWIXVFwcyShjI0KqkE2lra97SkDbyE707tz73PGtI1KwIlUTN6q1%2FQQ3NYVKCmewsB0Acabx%2F4sjGwVDFZIctzX9kaBf8GkCgJsWWFfiftxwRmk0x1YMDJItRppBVRmEhJ6nKiLGjtgyftZ2jcjfXR9a7x1vlA8Ppc%2F6fmlM%2FQ3z59lNrT39Tq2eQwRco%2FS0GLtJQBbYw79Sz2uGVQcaPNDik7T8%2B%2BcKWoraCYt7Jw%2BUXjx3y6gADVkyD%2BL6L83lWLlV3pg8pZyZ5Xnt9almeFbiWaTCrIcpNwx9Axcr%2FpscGPYpd%2FvwHTULH76KNH0%2F%2BkZ0iHzA1dTjszUQp0OMtVm9%2Bs5L0s0rzwut6SgJZliEnlXi4poCDgr6BGXaf2U8LhMfE%2F%2F6XWg2YstuucA9w8Q2yIBWCusPK1cTLUX%2B4fGDMKl4XzU8gsmCjcVnJ21MuIWo39AvAeaS%2FU4NCY4bgNQgh6O%2BCDGQNTt4PwOwIPvP83dTWxkE9ujTrRMFaiY4t49iq%2FVyMAsvrubcRAitiXyo%2B7XEftUeKpl7sBzU3H2rdioA9MXsPIuEcgriWuzSp53knPyUPqjmzjY2YfYlPXOhTbyG2jtjunvNaPgsEP%2BhUshFzXuoDi8UdAPPkTvaks%2Blwra0KeE13nI4Gplqgu%2FIo9%2Bic6Os%2FRnT9CLkHWn2aVfMsNIb5Vq4isMehJUNuoA5MMEGqxBCzq%2B5qFzT6ElhqPO%2FL%2Bfy4LJo2SXblqQs7XR8jcpjCCovmYBjqqAXEzTfEpDJlycWMKwuacIWQFd8zYlhLe0O18ekXiRbtM2g93la74hiPhe4GC7UPM5q5aHMSPvY0mWYlv8DaUuNr5bLqxZrKi%2BJdJ7VhwsyDsEsDhDmrzJ2Apxv5mHbTC00ET8AcsrY4ryFBf3Ab1LLywoUdAAJKmbkIPyhzYfixY1a4K4OC4HjX1%2FVQ8cqyDKxsuDCDUt6p5jog76N0HUIXx96Zmap7Q4Bth&amp;X-Amz-Algorithm=AWS4-HMAC-SHA256&amp;X-Amz-Date=20220911T215559Z&amp;X-Amz-SignedHeaders=host&amp;X-Amz-Expires=300&amp;X-Amz-Credential=ASIAQ3PHCVTYYU625WRQ%2F20220911%2Fus-east-1%2Fs3%2Faws4_request&amp;X-Amz-Signature=7026f5adfbaf497d49bca18ef086737e8f57da336bff28382a807f74c65945f2&amp;hash=b595c8d1829f44f593fe99d76314a4e3e37e30401b8d18aec23c0eecd07085d9&amp;host=68042c943591013ac2b2430a89b270f6af2c76d8dfd086a07176afe7c76c2c61&amp;pii=S1571066115000705&amp;tid=spdf-1ac63fbf-4383-48b8-9606-72a96f1ba1b9&amp;sid=57204baa57779446933891f7427b58b208begxrqa&amp;type=client&amp;ua=51505654035058505400&amp;rr=7493a6977f2cc0f0">An Introduction to Algebraic Effects and Handlers Paper</a></p><p><a href="https://github.com/reactjs/rfcs/blob/main/text/0213-suspense-in-react-18.md">rfcs/text/0213-suspense-in-react-18.md at main · reactjs/rfcs</a></p><ul><li>🌏글로벌 Top 교육 앱 QANDA(콴다)를 함께 만들어 갈 Frontend개발자들을 기다리고 있습니다!</li><li>🖥️콴다 팀의 개발 문화가 궁금하다면? ➡️ <a href="https://www.youtube.com/watch?v=9Xtm92NAU58">Inside QANDA: 최고의 글로벌 교육 서비스를 개발한다는 것</a></li><li>🕹️콴다 Frontend Team은 채용 중 입니다!➡️ <a href="http://bit.ly/3pVjlmR">공고 확인하기</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7454273f82e" width="1" height="1" alt=""><hr><p><a href="https://blog.mathpresso.com/conceptual-model-of-react-suspense-a7454273f82e">Conceptual Model of React Suspense</a> was originally published in <a href="https://blog.mathpresso.com/">Team QANDA</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Declarative React, and Inversion of Control]]></title>
            <link>https://blog.mathpresso.com/declarative-react-and-inversion-of-control-7b95f3fbddf5?source=rss-9ce465f93d9e------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b95f3fbddf5</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[febe]]></category>
            <category><![CDATA[product]]></category>
            <dc:creator><![CDATA[Yeoul]]></dc:creator>
            <pubDate>Tue, 06 Sep 2022 12:57:22 GMT</pubDate>
            <atom:updated>2023-02-22T04:33:36.608Z</atom:updated>
            <content:encoded><![CDATA[<h4>선언형 UI 라이브러리로서의 React에 대해 살펴봅니다.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7CMaL6oFkDNdrFkDdKQtaQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KrJ4sZ9q87BzEahpQwX1kQ.png" /><figcaption>Lin Clark — A Cartoon Intro to Fiber — React Conf 2017</figcaption></figure><h3>Overview</h3><p>React 공식문서의 <a href="https://ko.reactjs.org/docs/design-principles.html#scheduling">Design Principles</a> 부분을 보면, 다음과 같은 문구가 있습니다.</p><blockquote><strong>Even when your components are described as functions, when you use React you don’t call them directly.</strong><em> Every component returns a description of what needs to be rendered, and that description may include both user-written components like &lt;LikeButton&gt; and platform-specific components like &lt;div&gt;.</em><strong> It is up to React to “unroll” &lt;LikeButton&gt; at some point in the future and actually apply changes to the UI tree according to the render results of the components recursively.</strong></blockquote><p>요약하면 “컴포넌트가 함수(Functional Component)로 작성되어 있더라도, <strong>해당 컴포넌트를 렌더하고 DOM에 적용하는 것은 React의 책임</strong>이므로, 개발자가 리액트를 사용해서 개발할 때 직접 함수를 호출하지 않는다”는 의미인데, 이는 React의 설계원칙과 React가 지향하는 패러다임과 깊은 연관이 있습니다. 이번 포스팅에서는 이에 대해 살펴보도록 하겠습니다.</p><blockquote>콴다 프론트엔드 팀에서는 대부분의 웹 프로젝트와 웹뷰 프로젝트를 ReactJs + Typescript의 기술 스택(SEO대응, 저사양 디바이스에서의 성능 개선등을 위해 서버사이드 렌더링이 필요한 프로젝트의 경우에는 +NextJs)으로 개발하고 있기 때문에 React(이하 리액트)의 동작 원리에 대해서 많은 관심을 가지고 정리하고 공유하는 것을 중요하게 생각하고 있습니다.</blockquote><h3>Declarative React</h3><blockquote><em>In computer science, declarative programming is a programming paradigm </em><strong>that expresses the logic of a<em> computation without describing its control flow</em></strong><em>. -wiki(en)</em></blockquote><blockquote><em>선언형 프로그래밍은 두 가지 뜻으로 통용되고 있다. </em><strong><em>한 정의에 따르면, 프로그램이 어떤 방법으로 해야 하는지를 나타내기보다 무엇과 같은지를 설명하는 경우에 “선언형”</em></strong><em>이라고 한다. 또 다른 정의에 따르면, 프로그램이 함수형 프로그래밍 언어, 논리형 프로그래밍 언어, 혹은 제한형 프로그래밍 언어로 쓰인 경우에 “선언형”이라고 한다 -wiki(ko)</em></blockquote><p>React가 “선언적”(Declarative)인가에 대해 논하기 전에 먼저 선언적(Declarative)인 것이 무엇인가에 대해서 살펴보는 것이 좋습니다. 위에서 언급된 정의에 따르면 “선언형” 프로그래밍이란, 프로그램을 작성할 때 프로그램이 “어떤 방식으로” 목적지까지 도착할 것인지를 나타내는 것(Imperative. 명령형)이 아닌, 프로그램(혹은 상태)이 “무엇과 같은가”를 설명하는 것이라고 말합니다.</p><p>선언형과 명령형의 차이점에 대해 답변한 <a href="https://stackoverflow.com/a/1784702/19273716">stackoverflow 글</a>을 보면, Collection에서 odd numbers를 필터링하는 예제를 통해 이를 설명하고 있습니다. 명령형(Imperative) 프로그래밍의 경우 프로그램이 목적지까지 도착하기 위해 거쳐야 할 모든 단계들을 다음과 같이 컴파일러에게 알려줌으로써, 문제를 해결합니다.</p><ol><li>Create a result collection</li><li>Step through each number in the collection</li><li>Check the number, if it’s odd, add it to the results</li></ol><pre>List&lt;int&gt; results = new List&lt;int&gt;();<br>foreach(var num in collection)<br>{<br>    if (num % 2 != 0) results.Add(num);<br>}</pre><p>반면, 선언형 프로그래밍의 경우 프로그램이 목적지까지 도착하기 위해 어떻게 해야할지를 하나씩 알려주는 것이 아니라, &quot;<strong>내가 원하는 동작</strong>&quot;을 명시하는 코드를 작성합니다. (그 동작을 어떻게 수행할지에 대해서는 자세하게 명시할 필요가 없습니다.)</p><pre>var results = collection.Where( num =&gt; num % 2 != 0);</pre><blockquote><em>Here, we&#39;re saying &quot;Give us everything where it&#39;s odd&quot;, not &quot;Step through the collection. Check this item, if it&#39;s odd, add it to a result collection.&quot;</em></blockquote><p>그렇다면 선언형 프로그래밍과 명령형 프로그래밍의 이러한 차이가 User Interface의 관점에서는 어떤 것을 의미할까요? &lt;div&gt; 태그 안에 &lt;h1&gt; 태그가 있고, 그 안에 “Chocolate Cookie”라는 문구가 적힌 HTML 문서를 렌더링하고 싶다고 생각해보겠습니다. 명령형(Imperative) 프로그래밍 방식으로 이 UI를 렌더링하는 경우, 다음과 같이 DOM을 어떤 순서로 조작할지에 대해 하나씩 순차적으로 알려주어야 할 것입니다. <em>(For every interaction, we provide step-by-step DOM mutations to reach the desired state of UI.)</em></p><blockquote><em>The imperative approach is when you provide step-by-step DOM mutations until you reach desired UI</em></blockquote><pre>function addCookieToBody() {<br>  const bodyTag = document.querySelector(&#39;body&#39;)<br>  const divTag = document.createElement(&#39;div&#39;)</pre><pre>  let h1Tag = document.createElement(&#39;h1&#39;)<br>  h1Tag.innerText = &quot;Chocolate Cookie&quot;</pre><pre>  divTag.append(h1Tag)<br>  bodyTag.append(divTag)<br>}</pre><p>반면, 선언형(Declarative) 프로그래밍 방식으로 렌더링하는 경우, 해당 화면을 렌더링하기 위한 각각의 단계를 알려주는 것이 아니라, <strong>렌더링이 끝난 후에 보기를 원하는 최종 결과물을 “선언”하고, 해당 결과물을 렌더링하는 것은 UI 라이브러리의 책임으로 넘기게 됩니다.</strong> 그리고 바로 이것이 우리가 React를 사용해서 컴포넌트를 렌더링하는 방식입니다.</p><p>React를 사용해서 렌더링되어야 하는 컴포넌트를 개발할 때, 우리는 특정 상태에서 그려져야 하는 화면의 최종 모습을 React에게 전달하는 방식으로 개발합니다. 그리고 이 최종 모습을 렌더링하기 위해 task들을 스케줄링하고, DOM에 반영하는 것은 React의 책임이 됩니다. (<em>We don’t provide step-by-step instructions to reach the desired UI. Instead, we describe the final UI we want for each scene.</em>)</p><blockquote><em>The declarative approach is when you describe the final state of the desired UI</em></blockquote><pre>function RenderCookie() {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Chocolate Cookie&lt;/h1&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><p>React는 이렇게 “선언형” 방식으로 컴포넌트를 개발하도록 안내하고 있으며, 이에 따라 React 개발자는 매 렌더마다 DOM을 어떻게 조작할지에 대해 신경 쓸 필요없이, 특정 상태에 따른 최종 UI의 결과물을 “선언”해서 React Element의 형태로 React에 전달하고, 이를 DOM에 반영하는 것은 React의 책임으로 넘기게 됩니다.</p><blockquote><em>A declarative style, like what react has, allows you to control flow and state in your application by saying “It should look like this”. An imperative style turns that around and allows you to control your application by saying “This is what you should do”. — </em><a href="https://stackoverflow.com/questions/33655534/difference-between-declarative-and-imperative-in-react-js#:~:text=A%20declarative%20style%2C%20like%20what,is%20what%20you%20should%20do%22."><em>stackoverflow</em></a></blockquote><h3>Inversion of Control (IoC)</h3><blockquote><strong>your program would drive the prompts and pick up a response to each one</strong><em>. With graphical (or even screen based) UIs </em><strong>the UI framework would contain this main loop and your program instead provided event handlers for the various fields on the screen</strong><em>. </em><strong><em>The main control of the program was inverted, moved away from you to the framework. — Martin Fowler</em></strong></blockquote><p>이렇게 React에게 내가 그리고 싶은 UI를 React Element들의 묶음들로 “선언”해서 React에게 전달하면, React는 실제로 이 “선언”을 화면에 그리기 위한 작업들을 수행합니다. 이 과정을 통해 자연스럽게 DOM에 화면을 렌더할 책임이 개발자에서 React로 넘어오게 되며 이는 DOM을 조작해서 UI를 화면에 그리는 작업에 대한 제어권이 역전되었음(Inversion of Control)을 의미합니다. (<em>The main control of the program was inverted, moved away from you to react.)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/0*ApzSwXzY7V2qIQkc.png" /><figcaption>Lin Clark — A Cartoon Intro to Fiber — React Conf 2017</figcaption></figure><p>이렇게 “렌더링”에 대한 책임이 개발자에서 React로 넘어오게 됨으로써 얻게 되는 주요한 이점들이 있습니다.</p><h4>Fundamental Abstraction for Problem Solving</h4><blockquote><em>As you can see, the React way focuses on the result and further describes it in the render block of code. Simply put, “</em><strong><em>what I want rendered on the page is going to look like this and I don’t care about how you get there.</em></strong><em>”</em></blockquote><p>좋은 런타임은 직면한 문제와 일치하는 근본적인 추상화를 제공해 줍니다.(A good runtime provides fundamental abstractions that match the problem at hand) 여기서 추상화라는 것은 개발자가 표현하고자 하는 UI와 실제 이를 렌더링하기 위해 처리해야 하는 Task Splitting, Task Scheduling, Reconcilation, DOM Control 등의 작업을 “<strong>Anyway,</strong> <strong>React renders!</strong>” 한마디로 끝낼 수 있다는 것입니다. 이 추상화로 인해 우리는 “어떤 화면”을 렌더링할 것인지를 고민하는 데에 더 많은 시간을 사용할 수 있으며, 이 화면을 “어떻게” 렌더링해야 할 지에 대한 고민은 React 에게 온전히 맡길 수 있게 됩니다.</p><p>이는 “Clean Architecture”에서 이야기하는 Usecase와 같은 맥락에 있다고 할 수 있는데, 실제로 개발자는 Render라는 Usecase를 사용해서 UI를 선언하고, Render라는 기능이 어떻게 구현되어 있는지(Infrastructure), DOM은 언제 어떻게 조작하고, 각각의 Task들은 어떻게 나누는지등등에 대해서는 개발자가 신경쓸 필요가 없기 때문입니다. 이는 “<em>리액트의 책임” </em>입니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*fvS0QR6WaYAhUDAy.png" /><figcaption><a href="https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html">https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html</a></figcaption></figure><h4>Support for Concurrency &amp; Batching</h4><blockquote><em>This is a subtle distinction but a powerful one. Since you don’t call that component function but let React call it, </em><strong>it means React has the power to delay calling it if necessary</strong><em>. In its current implementation React walks the tree recursively and calls render functions of the whole updated tree during a single tick. However in the future it might start delaying some updates to avoid dropping frames.</em></blockquote><p>React가 Component의 Description(React Element들에 대한 정보)을 가지고 DOM을 조작해서 화면을 그리는 책임을 가져가게 된다는 것은 <em>React가 필요에 의해 렌더링을 위한 여러 작업들의 우선순위를 지정하거나, 작업을 수행하는 것을 미룰 수 있음을 의미 </em>합니다.</p><p>이는 React 18에서 소개된 “<a href="https://reactjs.org/blog/2022/03/29/react-v18.html#what-is-concurrent-react">Concurrent React</a>” 에서 확인할 수 있는데, User Event(Mouse Click, Keyboard Input)이벤트와 같이 상대적으로 빠르게 반영되어야 하는 이벤트들에 의한 렌더링 작업들을 우선적으로 처리하고, Background Data Fetching과 같은 이벤트들에 대해서는 상대적으로 나중에 반영하는 등의 성능 최적화를 React가 자체적으로 수행할 수 있음을 의미합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/0*Ova5tUS9i5UoLY60.png" /><figcaption>Lin Clark — A Cartoon Intro to Fiber — React Conf 2017</figcaption></figure><p>또한 브라우저가 매 프레임마다 작업을 수행하는 것을 가로막지 않기 위해 브라우저가 Call Stack을 차지하지 않는 시점에 렌더링 작업을 수행하게 할 수 있으며, 성능 최적화를 위해 개념상 동일한 작업들을 한번에 처리하는 Batching 처리들도 제공합니다. 이 모든 기능들을 React 에서 제공하고, 지속적으로 개선하며 유지보수하고 있기 때문에 개발자는 이를 신경쓰지 않아도 됩니다.</p><blockquote><em>If something is offscreen, we can delay any logic related to it. If data is arriving faster than the frame rate, we can coalesce and batch updates. We can prioritize work coming from user interactions (such as an animation caused by a button click) over less important background work (such as rendering new content just loaded from the network) to avoid dropping frames.</em></blockquote><p>이외에도 React가 렌더링에 대한 책임을 가져가게 됨으로써 얻을 수 있는 여러 이점들이 있는데, 추가적인 내용들은 Dan Abramov의 “<a href="https://overreacted.io/react-as-a-ui-runtime/">React as a UI runtime</a>” 글을 참고해주세요.</p><h3>Conclusion</h3><p>React는 UI 렌더링을 위한 라이브러리로, 개발자에게 <strong>런타임에 대한 좋은 추상화</strong>를 제공합니다. 이를 통해 개발자는 컴포넌트에 대한 선언만을 React Element의 형태로 React에게 제공하게 되며(Declarative), React는 개발자로부터 명세를 DOM에 반영할 책임을 넘겨받아 이를 렌더합니다.(IoC)</p><p>React가 지향하는 이러한 설계 원칙으로 인해, 개발자는 컴포넌트에 대한 선언을 유지한 채 React 버전을 업데이트하는 것 만으로도(e.g 17 to 18) 렌더링에 대한 성능을 끌어올릴 수 있으며, 사용자에게 제공해야 하는 “UI”, 즉 화면에 대해 더 심도깊은 고민을 할 수 있게 됩니다. React 공식문서의 한 부분을 인용하며 글을 마칩니다.</p><blockquote><em>React makes it painless to create interactive UIs. Design simple views for each state in your application, and React will efficiently update and render just the right components when your data changes.</em></blockquote><h3>Reference</h3><p><a href="https://martinfowler.com/articles/injection.html#InversionOfControl">https://martinfowler.com/articles/injection.html#InversionOfControl</a></p><p><a href="https://overreacted.io/react-as-a-ui-runtime/">https://overreacted.io/react-as-a-ui-runtime/</a></p><p><a href="https://alexsidorenko.com/blog/react-is-declarative-what-does-it-mean/">https://alexsidorenko.com/blog/react-is-declarative-what-does-it-mean/</a></p><p><a href="https://reactjs.org/docs/design-principles.html#scheduling">https://reactjs.org/docs/design-principles.html#scheduling</a></p><p><a href="https://en.wikipedia.org/wiki/Declarative_programming">Declarative programming - Wikipedia</a></p><ul><li>🌏글로벌 Top 교육 앱 QANDA(콴다)를 함께 만들어 갈 Frontend개발자들을 기다리고 있습니다!</li><li>🖥️콴다 팀의 개발 문화가 궁금하다면? ➡️ <a href="https://www.youtube.com/watch?v=9Xtm92NAU58">Inside QANDA: 최고의 글로벌 교육 서비스를 개발한다는 것</a></li><li>🕹️콴다 Frontend Team은 채용 중 입니다!➡️ <a href="http://bit.ly/3pVjlmR">공고 확인하기</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b95f3fbddf5" width="1" height="1" alt=""><hr><p><a href="https://blog.mathpresso.com/declarative-react-and-inversion-of-control-7b95f3fbddf5">Declarative React, and Inversion of Control</a> was originally published in <a href="https://blog.mathpresso.com/">Team QANDA</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>