notes

๐Ÿซ  Hydration Mismatch ๐Ÿซ  (2)2023. 6. 3.

์š”๊ธฐ์„œ ์ด๊ฒƒ ์ €๊ฒƒ ํ•ด๋ดค๋Š”๋ฐ ๋‹ค ๋ณ„๋กœ์ธ ๊ฒƒ ๊ฐ™๋‹ค. ์™œ๋ƒ๋ฉด ๋‹ค hydration mismatch๋ฅผ ํ•ด๊ฒฐํ•˜๋Š” ๊ฒŒ ์•„๋‹ˆ๊ณ  ํ”ผํ•ด๊ฐ€๋Š” ๊ฒƒ์ด๊ธฐ ๋•Œ๋ฌธ์ธ๋“ฏ...

๊ทธ๋Ÿฌ๋‹ˆ๊นŒ ์• ์‹œ๋‹น์ดˆ 'mismatch'๊ฐ€ ๋ฐœ์ƒํ•˜๋Š” ๊ฑด

  1. client state๊ฐ€ client์—์„œ๋งŒ ์•ก์„ธ์Šค ๊ฐ€๋Šฅํ•œ ๊ณณ์— persist ๋˜์–ด์žˆ์–ด์„œ
  2. server์—์„œ ์•ก์„ธ์Šค๊ฐ€ ์•ˆ๋˜๋‹ˆ๊นŒ
  3. UI ์ƒํƒœ๊ฐ€ ๋‹ฌ๋ผ์งˆ ์ˆ˜ ๋ฐ–์— ์—†๋‹ค.

์ธ๋ฐ ๊ทธ๋ ‡๋‹ค๋ฉด

  1. client state persist๋ฅผ
  2. server์—์„œ ์•ก์„ธ์Šค ๊ฐ€๋Šฅํ•œ ๊ณณ์— ํ•˜๋ฉด ๋˜๋Š” ๊ฒƒ์ž‰๊ฒŒ๋กฑ.

๊ทธ๋ž˜์„œ ์ข€ ์†์ด ๊ฐ€์ง€๋งŒ ๊ฑ ์ด๋ ‡๊ฒŒ ํ•ด๋ดค๋Š”๋ฐ,

  1. persist์—” cookie๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค.
  2. ์™œ๋ƒ๋ฉด ์ฟ ํ‚ค๋Š” ์„œ๋ฒ„ ์ปดํฌ๋„ŒํŠธ์—์„œ ์ฝ๊ธฐ ๊ฐ€๋Šฅ์ด๋ฏ€๋กœ. ์•”ํŠผ ๊ทธ๋ž˜์„œ ํ”Œ๋กœ์šฐ๋Š”,
  3. ์„œ๋ฒ„ ์ปดํฌ๋„ŒํŠธ์—์„œ cookie๋ฅผ ์ฝ์–ด์„œ ๊ณ  ์•ˆ์— ๋“ค์–ด์žˆ๋Š” persisted state๋ฅผ ๊ฐ€์ ธ์˜จ๋‹ค.
  4. mismatch๊ฐ€ ๋ฐœ์ƒํ•˜๋Š” ํด๋ผ์ด์–ธํŠธ ์ปดํฌ๋„ŒํŠธ์— ์œ„ state๋ฅผ ๋„˜๊ฒจ์ค„ prop์„ ํ•˜๋‚˜ ๋šซ๋Š”๋‹ค.
  5. ๊ทธ๋ฆฌ๊ณ  ๊ฐ™์€ ํด๋ผ์ด์–ธํŠธ ์ปดํฌ๋„ŒํŠธ์— useState๋กœ local state๋ฅผ ํ•˜๋‚˜ ๋งŒ๋“œ๋Š”๋ฐ,
  6. ๋งŒ๋“ค๋ฉด์„œ initialState๋กœ ์œ„ ์„œ๋ฒ„ ์ปดํฌ๋„ŒํŠธ์—์„œ ๋ฐ›์•„์˜จ prop์„ ๋„˜๊ฒจ์ค€๋‹ค.
  7. useEffect๋ฅผ ํ•˜๋‚˜ ์ถ”๊ฐ€ํ•ด์„œ
  8. ํด๋ผ์ด์–ธํŠธ ์ปดํฌ๋„ŒํŠธ๊ฐ€ ์“ฐ๊ณ  ์žˆ๋Š” persisted store์„ local state์— ๋ฌถ์–ด์ค€๋‹ค.
  9. ๊น…๊นŒ ๋Œ€๋žต
    export function useSyncedState<T>(clientState: T, serverState?: T) {
      const [state, setState] = React.useState<T>(serverState ?? clientState)
    
      React.useEffect(() => {
        setState(clientState)
      }, [clientState])
    
      return state
    }
    export function useSyncedState<T>(clientState: T, serverState?: T) {
      const [state, setState] = React.useState<T>(serverState ?? clientState)
    
      React.useEffect(() => {
        setState(clientState)
      }, [clientState])
    
      return state
    }
  10. ์™ˆ๋ฃŒ

์ด๋Ÿฌ๋ฉด

  1. ์–ด์ฐจํ”ผ ์„œ๋ฒ„๋„ ํด๋ผ์ด์–ธํŠธ๋„ ๊ฐ™์€ ๊ฑธ ๋ณด๊ณ  ์žˆ์œผ๋ฏ€๋กœ ์• ์‹œ๋‹น์ดˆ mismatch๊ฐ€ ์•„๋‹˜.
  2. hydration์ด ๋˜๊ธฐ ์ „์— ์ด๋ฏธ ๊ฐ™์€ ์ƒํƒœ์˜ UI๊ฐ€ ๋ณด์ด๋ฏ€๋กœ ๊นœ๋นก์ž„ ๊ฐ™์€ ๊ฒŒ ์—†์Œ.
๊ตณ

๊ทผ๋ฐ:

  1. ์„œ๋ฒ„ ํ˜ธ์ถœ์„ ํ•ด์•ผ ๋จ
  2. ๊ทธ๋ž˜์„œ ์š”๋ ‡๊ฒŒ ํ•œ ์ปดํฌ๋„ŒํŠธ๊ฐ€ ๋“ค์–ด์žˆ๋Š” ํŽ˜์ด์ง€๋Š” static export๊ฐ€ ์•ˆ๋จ

Tags