React useReducer

React/React 2022. 10. 13. 23:47
728x90

 

  • state : 현재 상태
  • dispatch : action을 발생시키는 함수
  • reducer : state와 action를 받아 새로운 state를 반환하는 함수
  • initialState : 초기값

 

useReducer 함수에는 첫번째 인자로 reducer 함수를, 두번째 인자로 초기 상태값을 넣어준다.

import React, { useReducer } from 'react';
 
function reducer(state, action) {
    switch (action.type) {
        case 'PLUS':
            return state + 1;
        case 'MINUS':
            return state - 1;
        default:
            return state;
    }
}
 
function Counter() {
    const [number, dispatch] = useReducer(reducer, 0);
 
    const onIncrease = () => {
        dispatch({ type: 'PLUS' });
    };
 
    const onDecrease = () => {
        dispatch({ type: 'MINUS' });
    };
 
    return (
        <div>
            <h1>{number}</h1>
            <button onClick={onIncrease}>+1</button>
            <button onClick={onDecrease}>-1</button>
        </div>
    );
}
 
export default Counter;

 

import logo from './logo.svg';
import './App.css';
import Counter from "./counter";
 
function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <Counter />
      </header>
    </div>
  );
}
 
export default App;
 

 

 

 

'React > React' 카테고리의 다른 글

React useMemo & useCallback  (0) 2022.10.24
React useRef 사용 예제  (0) 2022.10.15
React-bootstrap Header.js 테스트  (0) 2022.08.21
React CORS error 해결 방법  (0) 2022.08.20
React Query String  (0) 2022.06.08
블로그 이미지

Link2Me

,