FA/React

20221104 React Hooks - useReducer

๐Ÿ๐Ÿ๋ฆผ 2022. 11. 4. 23:04

Hook์˜ ๊ทœ์น™

  • React ํ•จ์ˆ˜ ๊ตฌ์„ฑ ์š”์†Œ ๋‚ด์—์„œ๋งŒ ํ˜ธ์ถœํ•  ์ˆ˜ ์žˆ์Œ(๋ฐ˜๋“œ์‹œ Functional Component ์•ˆ์—์„œ ์‚ฌ์šฉํ•ด์•ผ ํ•จ)
  • ๊ตฌ์„ฑ ์š”์†Œ์˜ ์ตœ์ƒ์œ„์—์„œ๋งŒ ํ˜ธ์ถœํ•  ์ˆ˜ ์žˆ์Œ
  • ์กฐ๊ฑด๋ฌธ, ๋ฐ˜๋ณต๋ฌธ ์•ˆ์—์„œ ๋ชป ์”€

useReducer 

 - useState์˜ ๋Œ€์ฒดํ•จ์ˆ˜

- ์ฝœ๋ฐฑ ๋Œ€์‹  ๋””์ŠคํŒจ์น˜๋ฅผ ์ „๋‹ฌ ํ•  ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ์ž์„ธํ•œ ์—…๋ฐ์ดํŠธ๋ฅผ ํŠธ๋ฆฌ๊ฑฐ ํ•˜๋Š” ์ปดํฌ๋„ŒํŠธ์˜ ์„ฑ๋Šฅ์„ ์ตœ์ ํ™” ํ•  ์ˆ˜ ์žˆ์Œ

- useReducer๋ฅผ ์‚ฌ์šฉํ•  ๋•Œ

  • ๋‹ค์ˆ˜์˜ ํ•˜์œ—๊ฐ’์„ ํฌํ•จํ•˜๋Š” ๋ณต์žกํ•œ ์ •์  ๋กœ์ง์„ ๋งŒ๋“œ๋Š” ๊ฒฝ์šฐ
  • state๊ฐ€ ์ด์ „ state์— ์˜์กด์ ์ธ ๊ฒฝ์šฐ์— ๋ณดํ†ต useState๋ณด๋‹ค useReducer๋ฅผ ์„ ํ˜ธ

reducer : state๋ฅผ ์—…๋ฐ์ดํŠธ ํ•ด์ฃผ๋Š” ์—ญํ• 

dispatch: state ์—…๋ฐ์ดํŠธ๋ฅผ ์œ„ํ•œ ์š”๊ตฌ

action: ์š”๊ตฌ์˜ ๋‚ด์šฉ

๋””์ŠคํŒจ์น˜๋กœ ์•ก์…˜(์š”๊ตฌ,์กฐ๊ฑด)์„ ํ•จ > ๋ฆฌ๋“€์„œ์„œ๋ฅผ ํ†ตํ•ด์„œ > ์Šคํ…Œ์ดํŠธ๊ฐ€ ์—…๋ฐ์ดํŠธ

dispatch(Actoin) > Reducer(State, Action)  > State Update

 

import { useReducer } from "react";

const [state, dispatch] = useReducer(reducer, initialArg, init);

const initialState = {count: 0};

function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return {count: state.count + 1};
    case 'decrement':
      return {count: state.count - 1};
    default:
      throw new Error();
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({type: 'decrement'})}>-</button>
      <button onClick={() => dispatch({type: 'increment'})}>+</button>
    </>
  );
}

 

 

์ฐธ๊ณ ์ž๋ฃŒ ๋ฐ ์ถœ์ €

https://ko.reactjs.org/docs/hooks-reference.html#usereducer

 

Hooks API Reference – React

A JavaScript library for building user interfaces

ko.reactjs.org

https://www.w3schools.com/react/react_usereducer.asp

 

React useReducer Hook

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com