← 문제 목록
고급 React 100P

React Hooks에서 상태 관리 방법

React Hooks를 사용하여 상태를 관리할 때, useState와 useReducer의 사용 차이에 대해 설명하고, 특정 상황에서 어떤 경우에 useReducer가 더 적합한지에 대해 논의합니다. 다음은 두 가지 훅을 사용하는 간단한 예시입니다:


이 코드에서 useState와 useReducer 각각의 장단점을 고려하여 어떤 시나리오에서 useReducer를 선택해야 하는지를 선택지에서 골라봅시다.
JAVASCRIPT
import React, { useState, useReducer } from 'react';

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();
  }
}

const Counter = () => {
  const [count, setCount] = useState(0);
  const [state, dispatch] = useReducer(reducer, initialState);
  
  return (
    <div>
      <h1>Count: {state.count}</h1>
      <button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
      <button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
    </div>
  );
};

답변

로그인 후 제출하기
0명 풀이 · 정답률 0%