useReducer

useReducer

Tags
Frontend
React
Published
Author

useReducer(reducer, initialArg, init?)

๋งค๊ฐœ๋ณ€์ˆ˜
  • reducer
    • state๊ฐ€ ์—…๋ฐ์ดํŠธ ๋˜๋Š” ๋ฐฉ์‹์„ ์ง€์ •ํ•˜๋Š” reducerํ•จ์ˆ˜์ž…๋‹ˆ๋‹ค.
    • state์™€ action์„ ์ธ์ž๋กœ ๋ฐ›์•„์•ผํ•˜๊ณ  ๋‹ค์Œ state๋ฅผ ๋ฐ˜ํ™˜ํ•ด์•ผํ•ฉ๋‹ˆ๋‹ค.
  • initialArg
    • ์ดˆ๊ธฐ state๊ฐ€ ๊ณ„์‚ฐ๋˜๋Š” ๊ฐ’์ž…๋‹ˆ๋‹ค.
  • optional init
    • ์ดˆ๊ธฐ state ๊ณ„์‚ฐ ๋ฐฉ๋ฒ•์„ ์ง€์ •ํ•˜๋Š” ์ดˆ๊ธฐํ™” ํ•จ์ˆ˜์ž…๋‹ˆ๋‹ค.

์ฃผ์˜์‚ฌํ•ญ

Strict Mode์—์„œ React๋Š” ์˜๋„์น˜ ์•Š์€ ๋ถˆ์ˆœ๋ฌผ์„ ์ฐพ๊ธฐ ์œ„ํ•ด reducer์™€ ์ดˆ๊ธฐํ™” ํ•จ์ˆ˜๋ฅผ ๋‘๋ฒˆ ํ˜ธ์ถœํ•ฉ๋‹ˆ๋‹ค.

dispatch function

useReducer๊ฐ€ ๋ฐ˜ํ™˜ํ•˜๋Š” dispatch ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด state๋ฅผ ๋‹ค๋ฅธ ๊ฐ’์œผ๋กœ ์—…๋ฐ์ดํŠธํ•˜๊ณ  ๋‹ค์‹œ ๋ Œ๋”๋ง์„ ์ด‰๋ฐœํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
React๋Š” reduce ํ•จ์ˆ˜์— ํ˜„์žฌ state์™€ dispatchํ•œ ์•ก์…˜์„ ์ „๋‹ฌํ•˜๊ณ  ๊ทธ ๊ฒฐ๊ณผ๋ฅผ ๋‹ค์Œ state๋กœ ์„ค์ •ํ•ฉ๋‹ˆ๋‹ค.
๋งค๊ฐœ๋ณ€์ˆ˜
  • action
    • ์‚ฌ์šฉ์ž๊ฐ€ ์ˆ˜ํ–‰ํ•œ ์ž‘์—…์ž…๋‹ˆ๋‹ค.
    • ๊ด€์šฉ์ ์œผ๋กœ๋Š” ์•ก์…˜์€ ๋ณดํ†ต ์ด๋ฅผ ์‹๋ณ„ํ•˜๋Š” type ์†์„ฑ์ด ์žˆ๋Š” ๊ฐ์ฒด์ด๋ฉฐ, ์„ ํƒ์ ์œผ๋กœ ์ถ”๊ฐ€ ์ •๋ณด๊ฐ€ ์žˆ๋Š” ๋‹ค๋ฅธ ์†์„ฑ์„ ํฌํ•จํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

์ฃผ์˜์‚ฌํ•ญ

  • dispatch ํ•จ์ˆ˜๋Š” ๋‹ค์Œ ๋ Œ๋”๋ง์— ๋Œ€ํ•œ state ๋ณ€์ˆ˜๋งŒ ์—…๋ฐ์ดํŠธํ•ฉ๋‹ˆ๋‹ค.
  • React๋Š” ์ปดํฌ๋„ŒํŠธ์™€ ๊ทธ ์ž์‹๋“ค์„ ๋‹ค์‹œ ๋ Œ๋”๋งํ•˜๋Š” ๊ฒƒ์„ ๊ฑด๋„ˆ๋œ๋‹ˆ๋‹ค.
import { useReducer } from 'react'; function reducer(state, action) { if (action.type === 'incremented_age') { return { age: state.age + 1 }; } throw Error('Unknown action.'); } export default function Counter() { const [state, dispatch] = useReducer(reducer, { age: 42 }); return ( <> <button onClick={() => { dispatch({ type: 'incremented_age' }) }}> Increment age </button> <p>Hello! You are {state.age}.</p> </> ); }

ํ•จ์ •

state๋Š” ์ฝ๊ธฐ ์ „์šฉ์ž…๋‹ˆ๋‹ค. state์˜ ๊ฐ์ฒด๋‚˜ ๋ฐฐ์—ด์„ ์ˆ˜์ •ํ•˜์ง€ ๋งˆ์„ธ์š”
function reducer(state, action) { switch (action.type) { case 'incremented_age': { // ๐Ÿšฉ Don't mutate an object in state like this: state.age = state.age + 1; return state; }
๋Œ€์‹  reducer๋กœ ๋ถ€ํ„ฐ ์ƒˆ๋กœ์šด ๊ฐ์ฒด๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋ฉด ๋œ๋‹ค.
function reducer(state, action) { switch (action.type) { case 'incremented_age': { // โœ… Instead, return a new object return { ...state, age: state.age + 1 }; }
ย 
ย