context-api사용법에 대한 더 자세한 정보는 여기
https://velog.io/@velopert/react-context-tutorial
mobx 를 공부하려다가
context-api로 하위 컴포넌트에게 전반적으로 props전달 하는 법도 모르고 있다는 것을 깨달았다.
각 컴포넌트에 로직을 일일히 작성하는 것보다 로직 파일을 따로 만들어 관리하는 것이 코드가 더 깔끔하다.
또 자식 컴포넌트들이 많은 경우 props를 아래 까지 전달시키는 코드를 짜는데 상당한 정신적 노동을 필요로 하는데 context-api는 이런 어려움에 대한 좋은 해결책이 된다.
그럼 만들어보자

import { createContext, ReactNode, useContext } from 'react';
import { View } from 'react-native';
import { GlobalLogics, TypeOfGlobalLogics } from '../../global_logic/global_logics';
type TypeOfHighestContext = TypeOfGlobalLogics;
// 1. createContext
// createContext 를 불러주면 자연스레 빨간줄이 그어짐
// (1)괄호안에 초기값을 넣어줘야하고 (2) 제네릭도 넣어주면 됨
const HighestContext = createContext<TypeOfHighestContext>(GlobalLogics);
// 2. () => useContext(HighestContext)
export const useHighestContext = () => useContext(HighestContext);
// 3. <HighestContext.provider value = {} >
type HighestProvider = {
children: ReactNode;
};
export const HighestProvider = ({ children }: HighestProvider) => {
return <HighestContext.Provider value={GlobalLogics}>{children}</HighestContext.Provider>;
};
context-api를 예쁘게 잘 만들었으니 적용 해보자
import { HighestProvider } from './src/components/hightest_context/highest_context';
export default function App() {
return (
<HighestProvider>
<NavigationContainer>
~~~
</NavigationContainer>
</HighestProvider>
);
}
이제 HighestProvider의 자식 컴포넌트들은 HighestProvider가 제공하는 로직을 받을 수 있게 된다
export function No9({ navigation }: any) {
const highestContext = useHighestContext();
return (
<ScrollView>
<QuestionPageBasicLayout
globalLogics={highestContext}
></QuestionPageBasicLayout>
</ScrollView>
);
}
이상입니다
나중에 내용 더 추가할 예정임