useReducer - 기초

jini.choi·2022년 5월 20일
0

React

목록 보기
19/21
  • 컴포넌트의 상태를 업데이트 해야할 때는 useState를 사용해서 새로운 상태를 설정해 줬는데,
    useReducerHook을 사용해서 상태 업데이트를 할 수 있다.

  • 차이점
    - useState: 설정하고 싶은 다음 상태를 직접 지정하여 상태 업데이트
    - useReducer: 액션 객체를 기반으로 상태 업데이트

  • 액션 객체라는 것은 업데이트할 때 참조하는 객체인데 type이라는 값을 이용해서 어떤 업데이트를 진행할건지 명시를 할수있고, 업데이트할 때 필요한 참조하고 싶은 다른 값이 있다면 객체 안에 넣을 수 도 있다.

  • 상태 업데이트 로직을 컴포넌트 밖으로 분리 가능

  • reducer는 현재 상태와 액션 객체를 파라미터로 받아와서 새로운 상태를 반환해주는 함수

function reducer(state, action){
	switch (action.type) {
		case 'INCREMENT':
			return state + 1;
		case 'DECREMENT':
			 return state - 1;
		default:
			return state;
}
  • useReducer를 사용할 땐 아래와 같다. 첫번째인자엔 reducer, 두번째 인자엔 기본값을 넣어줌

  • number는 현재상태 dispatch액션을 발생시키는 함수

const [number, dispatch] = useReducer(reducer, 0); 

dispatch는 ‘보내다’라는 의미를 가지고 있다.(여기서는 액션을 발생시킨다.)

dispatch({ type : 'INCREMENT' })

Counter.js

import React,{useReducer} from "react";

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

function Counter(){

    const [number, dispatch] = useReducer(reducer, 0);

    const onIncrease = () => {
        dispatch ({
            type: 'INCREMENT'
        })
    };
    const onDecrease = () => {
        dispatch ({
            type: 'DECREAMENT'
        })
    };

    return (
        <div>
            <h1>{number}</h1>
            <button onClick={onIncrease}>+1</button>
            <button onClick={onDecrease}>-1</button>
        </div>
    );
}

export default Counter;

index.js

index.js 파일을 열여서 App 대신 Counter를 랜더링하여 카운터가 잘 작동하는지 확인

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import Counter from './Counter';
import reportWebVitals from './reportWebVitals';

ReactDOM.render(
  <React.StrictMode>
    <Counter />
  </React.StrictMode>,
  document.getElementById('root')
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

이 글은 패스트캠퍼스 '프론트엔드(React)올인원패키지Online'을 수강하며 정리한 노트입니다.
https://fastcampus.co.kr/search?keyword=%ED%94%84%EB%A1%A0%ED%8A%B8%EC%97%94%EB%93%9C

profile
개발짜🏃‍♀️

0개의 댓글