[๐Ÿ’ŽReact] useReducer

h-a-n-aยท2023๋…„ 3์›” 25์ผ
1

๐Ÿ’ŽReact

๋ชฉ๋ก ๋ณด๊ธฐ
9/14

useReducer: ์ƒํƒœ ๊ด€๋ฆฌ๋ฅผ ๋‹ด๋‹นํ•˜๋Š” Hook
useState์™€ ๋น„์Šทํ•œ ๊ฐœ๋…์ด๋‚˜, useState๋ฅผ ํ†ตํ•œ ์ƒํƒœ๊ด€๋ฆฌ ๋ฐ ๋ฐ์ดํ„ฐ ์ถ”๊ฐ€/์ œ๊ฑฐ/์ˆ˜์ • ๋“ฑ์˜ ๊ฐ์ข… Handler๋ฅผ ์ผ์ผํžˆ ์“ธ ํ•„์š”์—†์ด ํ•˜๋‚˜์˜ ํ•จ์ˆ˜๋กœ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•ด์ค€๋‹ค.
useReducer์— ์ค‘์š”ํ•œ 3๊ฐ€์ง€ ๊ฐœ๋…์€ dispatch, action, Reducer.

const [state,dispatch] = useReducer(๋ฆฌ๋“€์„œ ์ด๋ฆ„, ์ดˆ๊ธฐ ๋ฐ์ดํ„ฐ)

state: ๋ง๊ทธ๋Œ€๋กœ ์ƒํƒœ ๊ทธ์ž์ฒด๋กœ, ๊ฐ์ข… ๋ฐ์ดํ„ฐ๊ฐ€ ๋“ค์–ด๊ฐ€๊ฒŒ ๋œ๋‹ค.
dispatch: ํ•ด๋‹น state์— ๋Œ€ํ•ด์„œ ์—…๋ฐ์ดํŠธํ•˜๊ธฐ ์œ„ํ•œ ์š”๊ตฌ dispatch(์ง„ํ–‰ํ•˜๊ณ ์ž ํ•˜๋Š” ์ž‘์—… ์ด๋ฆ„) ์œผ๋กœ ์ž‘์„ฑํ•˜๋ฉด ์ž‘์—…์ด ์ง„ํ–‰๋จ.
action: ์–ด๋–ค ์—…๋ฐ์ดํŠธํ• ์ง€ ์š”๊ตฌํ•˜๋Š” ๋‚ด์šฉ
reducer: state๋ฅผ ์—…๋ฐ์ดํŠธํ•˜๋Š” ์—ญํ• . state๋ฅผ ์—…๋ฐ์ดํŠธํ•˜๊ณ  ์‹ถ์„ ๋•Œ๋งˆ๋‹ค reducer๋ฅผ ํ†ตํ•ด dispatchํ•จ์ˆ˜๋ฅผ ๋ถˆ๋Ÿฌ์ค€๋‹ค.

์€ํ–‰(Reducer)์— ๊ฑฐ๋ž˜๋‚ด์—ญ์ด(State)๋ฅผ ๋ณ€๊ฒฝํ•ด๋‹ฌ๋ผ๊ณ  ์š”๊ตฌ(Dispatch).
์–ด๋–ค ๋ณ€๊ฒฝ์„ ์›ํ•˜๋Š”๋ฐ?(action) : ์†ก๊ธˆ

    const reducer = (state, action) => {
        // reducer๊ฐ€ returnํ•˜๋Š” ๊ฐ’์ด ์ƒˆ๋กœ ์—…๋ฐ์ดํŠธ๋  State
        // useState์™€ ๋งˆ์ฐฌ๊ฐ€์ง€๋กœ ์ปดํฌ๋„ŒํŠธ๊ฐ€ ๋ฐ”๋€”๋•Œ๋งˆ๋‹ค ์žฌ๋ Œ๋”๋งํ•ด์ค€๋‹ค
        switch (action.type) {
            case 'deposit':
                return state + action.payload
            case 'withdraw':
                return state - action.payload
            default:
                return state
        }
    }

๋ณ„์ฝ”๋”ฉ


  • ์˜ค๋Š˜ ์ƒˆ๋กญ๊ฒŒ ์•Œ๊ฒŒ ๋œ ์ :
    state ๋กœ์ง์ด ํ•œ ์ปดํฌ๋„ŒํŠธ์— ๋„ˆ๋ฌด ๋งŽ์ด์žˆ๊ฑฐ๋‚˜ ๋„ˆ๋ฌด ํฉ์–ด์ ธ ์žˆ์„ ๋•Œ ์˜ค๋Š” ๋ถˆํŽธํ•จ์„ useReducer์„ ํ†ตํ•ด ์ •๋ˆํ•  ์ˆ˜ ์žˆ๊ฒŒ ๋จ์„ ๋ฐฐ์› ๋‹ค.

  • ์˜ค๋Š˜ ๋ฐฐ์šด ๋‚ด์šฉ ์ค‘ ๋” ์•Œ๊ณ  ์‹ถ๊ฑฐ๋‚˜ ๊ถ๊ธˆํ•œ ์ :

  • ์˜ค๋Š˜์˜ ์†Œ๊ฐ:
    ์ฒ˜์Œ์—” ๊ทธ๋ƒฅ useState๋งŒ ์“ฐ์ง€, ์™œ ์ด๋ ‡๊ฒŒ๊นŒ์ง€ ํ•ด์•ผ ํ•˜๋‚˜..ํ–ˆ๋Š”๋ฐ useReducer์„ ์‚ฌ์šฉํ•จ์œผ๋กœ์จ ํ•จ์ˆ˜์˜ ์žฌ์‚ฌ์šฉ, ์ฝ”๋“œ์˜ ๊ฐ„๊ฒฐ์„ฑ ๋“ฑ์„ ์ƒ๊ฐํ•ด๋ณด๋‹ˆ ์ข‹์€ ๊ฐœ๋…์ด๋ผ๊ณ  ์ƒ๊ฐ์ด ๋“ค์—ˆ๋‹ค......

profile
ํ•˜๋ฃจํ•˜๋ฃจ๊ฐ€ ์—ฐ์Šต์ด๋‹ˆ ๋‚ด์ผ์€ ๋” ๊ฐ•ํ•ด์งˆ ๊ฒ๋‹ˆ๋‹ค

0๊ฐœ์˜ ๋Œ“๊ธ€