본문 바로가기
React

230628 useState / useReducer

by hyerin1201 2023. 6. 28.

useState ( ) 는 컴포넌트 내에서만 사용사능.

많은 내용이 사용될경우, 컴포넌트가 비대해질 수 있다.

 

useReducer 사용방법

*const [count(*변수), dispatch(*상태변화촉발함수)] = useReducer( reducer, 0 ) *두개의 인자값 리듀서(상태변화함수), 초기값 ====> component 안에 쓰임

*reducer : 역시 두개의 인자값을 받음 reducer( state, action)  ===> state는 상태변화의 최종값, action은 디스패치에 사용된 객체(즉 액션객체)

*dispatch 상태변화의 촉발함수 인자값은 무조건 객체타입

 

function reducer(state, action) {
  switch (action.type) {
    case "INCREASE":
      return state + action.data;
    case "DECREASE":
      return state - action.data;
    case "INIT":
      return 0;
    default:
      return state;
  }
}

function App() {
  // const [count, setCount] = useState(0);
  // const onIncrease = () => {
  //   setCount(count + 1);
  // };
  // const onDecrease = () => {
  //   setCount(count - 1);
  // };
  const [count, dispatch] = useReducer(reducer, 0);

  return (
    <div className="App">
      <h4>test component</h4>
      <div>
        <h1>{count}</h1>
        {/* <h1>{count}</h1> */}
      </div>
      <div>
        <button onClick={() => dispatch({ type: "INCREASE", data: 1 })}>
          +
        </button>
        <button onClick={() => dispatch({ type: "DECREASE", data: 1 })}>
          -
        </button>
        <button onClick={() => dispatch({ type: "INIT" })}>0으로 초기화</button>
        {/* <button onClick={onIncrease}>+</button>
        <button onClick={onDecrease}>-</button> */}
      </div>
    </div>
  );
}

export default App;