<aside> <img src="https://s3-us-west-2.amazonaws.com/secure.notion-static.com/f765100f-b481-437e-b531-5aae8d9bc5fe/1200px-React-icon.svg.png" alt="https://s3-us-west-2.amazonaws.com/secure.notion-static.com/f765100f-b481-437e-b531-5aae8d9bc5fe/1200px-React-icon.svg.png" width="40px" /> 리액트를 공부하면서 기록합니다.
</aside>
상위 컴포넌트에서 하위 컴포넌트로 속성을 내려주는 것으로 편하게 UI를 구성할 수 있다는 것이 리액트가 가진 장점이자 단점이다.
만약 상위 컴포넌트와 하위 컴포넌트 간의 깊이가 깊고, 사이에 다른 컴포넌트의 발생으로 간격이 길어질 수 있다. 그럴 경우 그 사이에서 단순하게 props만 내려주는 불필요한 컴포넌트가 생긴다.
이것을 방지하고, 전역적으로 속성값을 사용할 수 있게 해주는 hook이 Context이다.
import { createContext } from 'react'
const UserContext = createContext('username');
createContext('values') 를 사용해서 context 객체를 생성한다.<UserContext.Provider value="하위 컴포넌트로 내려줄 속성값" />
<UserContext.Consumer>
{ username => <p>{`${username}님 안녕하세요.`}</p>}
</UserContext.Consumer>
// 보통은 이렇게 사용해요
const username = useContext(UserContext);
return <p>{username}님 안녕하세요.</p>
Provider 내부의 value 속성에 들어있는 값이 하위 컴포넌트에 전달되는 속성값이다.Consumer 요소가 반영된 하위 컴포넌트는 중간 다리 없이 그 속성값을 사용할 수 있다. 가장 가까운 Provider의 value를 찾는다. Provider를 찾지 못하면 초기에 create에 넣어준 기본값이 반영된다.useContext(context_obj) 형태로 값을 불러내어 컴포넌트에 사용한다.// 이렇게 콜백을 컨텍스트 객체로 만들어줄 수 있다.
const SetCountContext = createContext(() => {});
const [count, setCount] = useState(0);
return (
<SetUserContext.Provider(setCount) />
...
const setCounter = useContext(SetUserContext); // -> setUser 함수 전달
return (
<button onClick={() => setCounter(count + 1))> 증가 </button>
)