You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: _posts/2025-01-14-how-to-use-usecontext.md
+56-7Lines changed: 56 additions & 7 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -100,7 +100,7 @@ Context가 뭔데? 라고 하신다면 전역 데이터를 담고 있는 하나
100
100
```jsx
101
101
import { createContext } from"react";
102
102
103
-
constcontext=useContext()
103
+
constcontext=createContext()
104
104
```
105
105
<br/>
106
106
@@ -121,7 +121,7 @@ Initial Value에서 `value` 속성값을 지정하지 않을 경우, Context를
121
121
{% raw %}
122
122
import { createContext } from"react";
123
123
124
-
constContext=useContext()
124
+
constContext=createContext()
125
125
126
126
functionExample() {
127
127
const [title, setTitle] =useState('useContext')
@@ -142,6 +142,47 @@ function Example() {
142
142
{% endraw %}
143
143
```
144
144
value로는 넘겨줄 값을 넣으면 됩니다.
145
+
#### ⚠️ 주의
146
+
여기서 주의할 점은 Context로 관리할 <spanstyle='color: indianred'>**상태를 최상단 부모 컴포넌트에 위치시키면 안 된다**</span>는 점입니다.
147
+
148
+
최상위 부모 컴포넌트에 상태를 위치시키면 Context API를 사용하는 의미가 없어집니다. 최상단에 위치해있기 때문에 상태가 변하면 자식들의 리렌더링이 발생할 수 밖에 없기 때문이에요.
149
+
150
+
그래서 보통은 Provider 컴포넌트를 하나 만들어서, 무조건 Provider 컴포넌트 안에 관리할 상태를 넣어 리렌더링 발생을 막습니다.
151
+
152
+
```jsx
153
+
{% raw %}
154
+
import { createContext } from"react";
155
+
156
+
constContext=createContext()
157
+
158
+
functionContextProvider({ children }) {
159
+
const [title, setTitle] =useState('useContext')
160
+
const [content, setContent] =useState('Context provides a way to pass data through the component tree without having to pass props down manually at every level')
const [content, setContent] =useState('Context provides a way to pass data through the component tree without having to pass props down manually at every level')
{"@context":"https://schema.org","@type":"WebSite","dateModified":"2025-01-14T21:07:02+09:00","datePublished":"2025-01-14T21:07:02+09:00","description":"Add Markdown syntax content to file _tabs/about.md and it will show up on this page.","headline":"About","name":"이어진","sameAs":["https://github.com/oding01"],"url":"http://localhost:4000/about/"}</script>
45
+
{"@context":"https://schema.org","@type":"WebSite","dateModified":"2025-01-15T12:03:55+09:00","datePublished":"2025-01-15T12:03:55+09:00","description":"Add Markdown syntax content to file _tabs/about.md and it will show up on this page.","headline":"About","name":"이어진","sameAs":["https://github.com/oding01"],"url":"http://localhost:4000/about/"}</script>
0 commit comments