Mobile/react-native
[react-native] typescript로 Context API 사용 예제
춘햄
2024. 2. 21. 08:36
typeScript로 contextAPI 를 사용하는 context 컴포넌트를 만들면 createContext로 사용할 전역 변수를 인터페이스로 만들어서 관리가 가능하다는 점과 제네릭 설정을 넣어 null 값에 대한 exception 처리를 손쉽게 할 수 있다는 장점이 있다.
바로 바로 참고할 수 있게 간단한 예제 컴포넌트만 하나 확인해보자.
◎AuthContext.tsx
import React, {createContext, useContext, useState} from 'react';
interface User {
id: number;
username: string;
}
interface AuthContextValue {
user: User | null;
setUser(user: User): void;
}
const AuthContext = createContext<AuthContextValue | null>(null);
export const AuthContextProvider = ({
children,
}: {
children: React.ReactNode;
}) => {
const [user, setUser] = useState<User | null>(null);
return (
<AuthContext.Provider value={{user, setUser}}>
{children}
</AuthContext.Provider>
);
};
export const useAuth = () => {
const auth = useContext(AuthContext);
if (!auth) {
throw new Error('AuthContextProvider is not used');
}
return auth;
};
조금... 더 편해졌나..? 확실히 엉뚱한 값을 context 함수에 넣어 발생하는 런타임 에러를 없앨 수 있어 보인다.
반응형