next.js에서 zustand를 쓸 때는 주의해야 한다

next.js에서 zustand를 쓸 때는 주의해야 한다

생성일
May 11, 2024 06:58 AM
태그
nextjs
zustand
  • next.js는 SSR을 이용하고 있다.
  • zustand는 전역변수를 활용해 상태관리를 한다
  • 바람직한 상태관리는 request단위로 이뤄져야지, 여러 request가 하나의 상태를 공유해서는 안 된다.
 
 
이런식으로 store마다 provider를 만들어 활용해줘야만 한다.
// src/providers/counter-store-provider.tsx 'use client' import { type ReactNode, createContext, useRef, useContext } from 'react' import { type StoreApi, useStore } from 'zustand' import { type CounterStore, createCounterStore } from '@/stores/counter-store' export const CounterStoreContext = createContext<StoreApi<CounterStore> | null>( null, ) export interface CounterStoreProviderProps { children: ReactNode } export const CounterStoreProvider = ({ children, }: CounterStoreProviderProps) => { const storeRef = useRef<StoreApi<CounterStore>>() if (!storeRef.current) { storeRef.current = createCounterStore() } return ( <CounterStoreContext.Provider value={storeRef.current}> {children} </CounterStoreContext.Provider>) } export const useCounterStore = <T,>( selector: (store: CounterStore) => T, ): T => { const counterStoreContext = useContext(CounterStoreContext) if (!counterStoreContext) { throw new Error(`useCounterStore must be use within CounterStoreProvider`) } return useStore(counterStoreContext, selector) }
 
 

결론

Next.js에서 Zustand를 쓰는 것은 추천하지 않고 싶다.
별로라서가 아니다.
Zustand의 최대 장점이 간결성과 최소한의 boilerplate인데, 이 장점이 훼손되기 때문이다.