> For the complete documentation index, see [llms.txt](https://hxxtae.gitbook.io/welaundry-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://hxxtae.gitbook.io/welaundry-docs/state-management.md).

# State Management

welaundry의 인증 상태 관리에 대한 관심사 분리를 설명합니다.

<figure><img src="https://user-images.githubusercontent.com/79623316/184597533-a16a7ec1-5181-42d6-9bce-f9c822ee4810.svg" alt=""><figcaption></figcaption></figure>

### useAuthFetch

```typescript
export const userState = atom<string | undefined>({
  key: 'user',
  default: undefined,
});

export const useAuthFetch = (): IAuthFetch => {
  const [user, setUser] = useRecoilState(userState);
  const authService = useRecoilValue(authApi);

  const { isLoading } = useQuery(queryKeys.auth.me(), () => authService.me(), {
    retry: false,
    refetchOnWindowFocus: false,
    onSuccess: (data) => {
      setUser(data?.data.username);
    },
  }); 

  return { user, isLoading }
}
```

### AuthContext

```tsx
const AuthContext = ({ children }: IAuthContextProps) => {  
  const { user, isLoading } = useAuthFetch();

  return (
    <>
      {
        isLoading ? <LoginLoading /> :
        user ? children : <NonUserRouter />
      }
    </>
  )
}
export default AuthContext;
```

* 위 코드는 사용자 인증 성공 여부에 따른 라우터된 화면을 보여줍니다.
* `Server(React-Query)`에서 응답한 사용자의 정보를 받아 `Client(Recoil)`의 전역 상태로 관리되어 집니다.
* 비즈니스 로직과 UI로직을 따로 분리하기 위해 `useAuthFetch` 라는 Custom Hook을 만들어 인증에 대한 상태를 선언형으로 쉽게 사용하도록 하였습니다.
