[Hook] useReducer

๊ฐ•์€๋น„ยท2022๋…„ 1์›” 12์ผ
0

React

๋ชฉ๋ก ๋ณด๊ธฐ
11/36
post-custom-banner

react ์Šคํ„ฐ๋””์—์„œ ๋ฆฌ์•กํŠธ๋ฅผ ๋‹ค๋ฃจ๋Š” ๊ธฐ์ˆ ์ด๋ผ๋Š” ์ฑ…์„ ์„ ์ •ํ–ˆ๊ณ  ์ด ์ฑ…์„ ์ฝ๊ณ  ๋ฐฐ์šด ๊ฒƒ์„ ๋ฐ”ํƒ•์œผ๋กœ ์ž‘์„ฑ๋˜์—ˆ๋‹ค.


๐Ÿ“Œ useReducer

  • useState๋ณด๋‹ค ๋” ๋‹ค์–‘ํ•œ ์ปดํฌ๋„ŒํŠธ ์ƒํ™ฉ์— ๋”ฐ๋ผ ๋‹ค์–‘ํ•œ ์ƒํƒœ๋ฅผ ์—…๋ฐ์ดํŠธํ•ด์ฃผ๊ณ  ์‹ถ์„ ๋•Œ ์‚ฌ์šฉํ•œ๋‹ค.

๐Ÿ’ก useReducer๋ฅผ ์‚ฌ์šฉํ–ˆ์„ ๋•Œ์˜ ํฐ ์žฅ์ ์€ ์ปดํฌ๋„ŒํŠธ ์—…๋ฐ์ดํŠธ ๋กœ์ง์„ ์ปดํฌ๋„ŒํŠธ ๋ฐ”๊นฅ์œผ๋กœ ๋นผ๋‚ผ ์ˆ˜ ์žˆ๋‹ค.

โœจ reducer

  • ํ˜„์žฌ ์ƒํƒœ(state)์™€ ์—…๋ฐ์ดํŠธ๋ฅผ ์œ„ํ•ด ํ•„์š”ํ•œ ์ •๋ณด๋ฅผ ๋‹ด์€ action ๊ฐ’์„ ์ „๋‹ฌ๋ฐ›์•„ ์ƒˆ๋กœ์šด ์ƒํƒœ๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜์ด๋‹ค.
  • ๋ถˆ๋ณ€์„ฑ์„ ์ง€ํ‚ค๋ฉด์„œ ์—…๋ฐ์ดํŠธ๋œ ์ƒˆ๋กœ์šด ์ƒํƒœ๋ฅผ ๋ฐ˜ํ™˜ํ•ด์•ผ ํ•œ๋‹ค.
  • action ์€ ์–ด๋–ค ๊ฐ’๋„ ์‚ฌ์šฉ ๊ฐ€๋Šฅํ•˜๋‹ค.
function reducer(state, action){
    return {};
}

โœจ state, dispatch

  • useReducer์˜ ์ฒซ๋ฒˆ์งธ ์ธ์ž์—๋Š” reducerํ•จ์ˆ˜๋ฅผ ๋„ฃ๊ณ , ๋‘๋ฒˆ์งธ ์ธ์ž์—๋Š” ์ดˆ๊ธฐ ์ƒํƒœ๊ฐ’์„ ๋„ฃ๋Š”๋‹ค.
  • useReducer๋ฅผ ํ˜ธ์ถœํ•˜๊ณ  ๋น„๊ตฌ์กฐํ™” ํ• ๋‹น์„ ํ†ตํ•ด state์™€ dispatch๋ฅผ ์ถ”์ถœํ•œ๋‹ค.
  • state๋Š” ํ˜„์žฌ ์ƒํƒœ๊ฐ’์ด๊ณ , dispatch๋Š” action๊ฐ’์„ ์ธ์ž๋กœ ๋ฐ›์•„ reducerํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•˜๋Š” ํ•จ์ˆ˜์ด๋‹ค. (dispatch(action)

์˜ˆ์‹œ

// Counter
import { useReducer } from 'react';

function reducer(state, action){
    switch(action.type){
        case "INCREMENT":
            return { value: state.value + 1};
        case "DECREMENT":
            return { value: state.value - 1};
        default:
            return state;
    }
}


const Counter = () => {
    const [state, dispatch] = useReducer(reducer, { value: 0 });
    return (
       <div>
           <h1>number : {state.value}</h1>
           <button onClick={() => dispatch({type: "INCREMENT"})}>+1</button>
           <button onClick={() => dispatch({type: "DECREMENT"})}>-1</button>
       </div>
    );

}
post-custom-banner

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