본문 바로가기

JavaScript

Context API [React]

Context API

If we use 'context', we don't need pass props to each layer. we can pass values using context just at once.
For example, Usually it is used for current authenticated user, preferred language.

React.createContext

const MyContext = React.createContext(defaultValue);

When React renders a component that subscribes to this Context object it will read the current context value from the closest matching Provider above it in the tree.

The defaultValue argument is only used when a component does not have a matching Provider above it in the tree.

Context.Provider

<MyContext.Provider value={/* some value */}>

Every Context object comes with a Provider React component that allows consuming components to subscribe to context changes.

Accepts a value props to be passed to consuming components that are descendants of this Provider. All consumers that are descendants of a Provider will re-render whenever the Provider's value prop changes.

Context.Consumer

<MyContext.Consumer>
    {value => /* render something based on the context value */}
</MyContext.Consumer>

This is React component that subscribes to context changes.

Requires a function as a child.
The function receives the current context value and returns a React node. The value argument passed to the function will be equal to the value prop of the closest Provider for this context above in the tree.

'JavaScript' 카테고리의 다른 글

웹서비스에 채팅 기능 추가.  (0) 2020.09.16
Process of showing datas to client [React]  (0) 2020.07.29
Hooks code example [React]  (0) 2020.07.27
Component keywords [React]  (0) 2020.07.27
node / express 공부기.  (0) 2020.04.25