[React Native] Recoil

narinn-star·2023년 1월 18일
0

상태 관리 라이브러리, Recoil을 사용해보자!

Recoil?

페이스북에서 만든, React를 위한 상태 관리 라이브러리이다.
Redux는 아직 사용해보지 않아서 둘의 명확한 차이는 잘 모르지만, Recoil을 한 번 사용해 보았을 때 React 내장 Hooks와 사용하는 방식이 비슷해 크게 어렵지 않았다.
그저 useState를 useRecoilState로 작성하기만 하면 된다.

Recoil 공식 문서에서는 "Recoil을 사용하면 atoms에서 selectors를 거쳐 React 컴포넌트로 내려가는 data-flow graph를 만들 수 있다." 라고 소개한다.

Atoms

Atoms는 상태의 단위이다. 업데이트와 구독이 가능하며, atom이 업데이트 되면 새로운 값을 반영해 리렌더링 된다. 동일한 atom이 여러 컴포넌트에서 사용된다면 모두 한 상태를 공유하게 된다.

Selectors

atoms의 상태값을 동기 또는 비동기 방식을 통해 변환하는 순수 함수이다. 상위 atoms나 selecotrs가 업데이트 되면 하위의 selector 함수도 다시 실행되며, atoms 처럼 구독이 가능하고 변경되면 컴포넌트들도 리렌더링 된다.

Recoil 시작하기

🔧 설치

yarn add recoil

RecoilRoot

루트 컴포넌트 (Ex_App.tsx)에 RecoilRoot로 전체를 감싸주어야 한다.

App.tsx

...
import { RecoilRoot } from "recoil";

const Stack = createNativeStackNavigator<RootStackParamList>();

export default function App() {
	return (
		<RecoilRoot>
			<NavigationContainer>
				<Stack.Navigator initialRouteName="Home">
					<Stack.Screen
						name="Home"
						component={Home}
						options={{ title: "Home" }}
					/>
					<Stack.Screen
						name="Login"
						component={Login}
						initialParams={{ name: "Login", userId: "User" }}
						options={{ title: "로그인" }}
					/>
				</Stack.Navigator>
				<StatusBar style="auto" />
			</NavigationContainer>
		</RecoilRoot>
	);
}

authState

auth에 대한 정보 저장할 거라서, 아래처럼 authState 작성했다.
email과 password를 저장하기 위해 interface도 정의했다.

recoil/auth.tsx

import { atom } from "recoil";

export interface IAuthTypes {
	email: string;
	password: string;
}

const authState = atom({
	key: "authState",
	default: null,
});

export default authState;

auth, setAuth

이제 authState를 사용해서 저장해보장!

Login/index.tsx 일부

import authState, { IAuthTypes } from "../../recoil/auth";
import { useRecoilState } from "recoil";
...

const Login = ({ navigation }: Props) => {
	const [auth, setAuth] = useRecoilState<IAuthTypes[]>(authState);
    ...
    return (
    	<Container>
        	...
        	<Button
				style={{ marginBottom: 24 }}
				label="Login"
				onPress={() => {
					setAuth([{ email: username, password: password }]);
                }
            />
            <Button
            	style={{ marginBottom: 24 }}
                label="Confirm"
                onPress={() => {
                	console.log(auth);
                }
            />
            ...
        </Container>
    );
};

export default Login;

어디서든 useRecoilState<>(authState)만 사용하면, 또는 useRecoilValue만 사용하면 저장해둔 값을 사용할 수 있다.

0개의 댓글