본문 바로가기
프로그래밍/React

[React] createContext

by YuminK 2023. 11. 29.

createContext

createContext lets you create a context that components can provide or read.

const SomeContext = createContext(defaultValue)

 

Parameters 

  • defaultValue: The value that you want the context to have when there is no matching context provider in the tree above the component that reads context. If you don’t have any meaningful default value, specify null. The default value is meant as a “last resort” fallback. It is static and never changes over time.

Returns 

createContext returns a context object.

The context object itself does not hold any information. It represents which context other components read or provide. Typically, you will use SomeContext.Provider in components above to specify the context value, and call useContext(SomeContext) in components below to read it. The context object has a few properties:

  • SomeContext.Provider lets you provide the context value to components.
  • SomeContext.Consumer is an alternative and rarely used way to read the context value.

 

프로바이더로 컴포넌트를 감싸면 내부 컴포넌트에서 useContext를 이용하여 값을 받을 수 있다. (깊이는 상관없음) 컨텍스트는 props의 전달없이 정보를 넘길 수 있다. 또한 useContext를 사용하여 값을 받는 컴포넌트는 context가 변경되면 재렌더링된다. 컨텍스트를 생성할 때 사용하는 기본값은 오직 매칭되는 Provider를 찾을 수 없을 때 호출되는 Fallback이다. 

'프로그래밍 > React' 카테고리의 다른 글

Nextjs 정리  (0) 2024.01.10
[React] useReducer  (0) 2023.11.30
[React] useContext  (0) 2023.11.29
[React] forwardRef  (0) 2023.11.29
[React] memo  (1) 2023.11.29

댓글