Web/React

[React] useReducer 컴포넌트에서 상태변화 로직 분리

usingsystem 2023. 4. 24. 11:16
728x90

컴포넌트 내에서 함수가 많아지고 길어지는 방법은 복잡해지기 때문에 올바른 방법이라고 할 수 없다.

 

useReducer은 컴포넌트의 상태변화 로직을 컴포넌트 밖으로 분리하여 사용할 수 있다.

 

reducer

const reducer = (state, action) => {
 switch (action.type) {
 	case 1:
    	return state +1;
 	case 2:
    	return state +2;
 	case 3:
    	return state +3;
    default:
    	return state;
  }
 );

형식

const reducer = (상태변화가 일어나기전 status, 어떤 상태변화를 일으킬 지의 action 객체) =>{

switch(action.type){

     return 새로운 상태 값

  }

}

dispatch

const Counter = () =>{
 const [count, dispatch] = useReducer(reducer, 1);
 
 return (
  <div>
  	{count}
 	<button onClick={() => dispatch({ type: 1 })}>add 1 </button>
  	<button onClick={() => dispatch({ type: 2 })}>add 2 </button>
  	<button onClick={() => dispatch({ type: 3 })}>add 3 </button>
  </div>
 );
 };

dispatch를 사용하면 reducer에게 action을 넘겨주게 된다.

 

형식

 const [count, dispatch] = useReducer(상태변화함수, 초기값);

728x90