Context 공급자

Context provider

공급자 아래의 깊은 자식들이 중간 props 전달 없이 같은 값을 읽습니다.

···
html
<div class="scene"><div class="provider" id="provider">ThemeContext <b>mint</b></div><div class="branches"><div class="branch"><div class="middle">Layout</div><div class="consumer" id="first">Toolbar: mint</div></div><div class="branch"><div class="middle">Page → Panel</div><div class="consumer" id="second">Button: mint</div></div></div><div class="label">intermediate nodes pass no theme prop</div></div>
css
.scene{width:min(94vw,800px);height:min(86vh,320px);position:relative;overflow:hidden;display:flex;flex-direction:column;justify-content:space-between;border:1px solid var(--line);border-radius:14px;background:var(--surface);padding:clamp(9px,2.4vmin,20px);font:500 clamp(15px,4vmin,18px)/1.3 var(--font-sans,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif)}.scene b,.scene strong{font-weight:700}.label{color:var(--muted)}.code{font-family:ui-monospace,SFMono-Regular,Consolas,monospace}.pill{border:1px solid var(--line);border-radius:8px;padding:.4em .65em;background:var(--bg)}.active{border-color:var(--accent)!important;color:var(--accent)!important;background:color-mix(in srgb,var(--accent) 10%,var(--surface))!important}.provider,.middle,.consumer{border:1px solid var(--line);border-radius:7px;text-align:center;padding:clamp(4px,1.6vmin,7px);font-size:clamp(12px,3vmin,15px)}.provider{border-color:var(--accent);font-weight:700}.provider b{color:var(--accent)}.branches{display:flex;gap:8px;flex:1;margin-top:8px}.branch{flex:1;display:flex;flex-direction:column;justify-content:space-around;align-items:stretch;border-top:2px solid var(--accent);position:relative}.branch:before{content:"";position:absolute;top:-9px;left:50%;height:8px;border-left:2px solid var(--accent)}.middle{color:var(--muted)}.consumer{background:color-mix(in srgb,var(--accent) 13%,var(--surface));border-color:var(--accent);font-weight:700}.consumer.pulse{animation:pulse .65s ease}@keyframes pulse{50%{transform:scale(1.04);background:color-mix(in srgb,var(--accent) 28%,var(--surface))}}.label{text-align:center;font-size:clamp(12px,3vmin,14px)}
js
const themes=["mint","amber","blue"];let n=0;function tick(){const theme=themes[n%3];document.querySelector(".provider b").textContent=theme;for(const [id,label] of [["first","Toolbar"],["second","Button"]]){const el=document.getElementById(id);el.textContent=label+": "+theme;el.classList.remove("pulse");void el.offsetWidth;el.classList.add("pulse")}n++}tick();setInterval(tick,1100)

Context 공급자는 컴포넌트 트리의 한 범위에 값을 제공하고, 아래의 소비자는 useContext로 가장 가까운 공급자의 값을 읽습니다. 테마나 현재 언어처럼 많은 자식이 함께 사용하는 값에 적합합니다.

데모는 공급자 값을 바꾸면 여러 깊이의 소비자가 함께 갱신되는 트리입니다. Context 값이 바뀌면 이를 읽는 소비자가 다시 렌더되므로 변화가 잦은 모든 상태를 한 곳에 넣기보다 범위를 나눕니다.

언제 쓰나

깊은 트리에서 여러 컴포넌트가 같은 테마·언어·설정 값을 읽을 때 사용합니다.

페이지로 열기 ↗