[React]Additional Hooks(useReducer)

M_yeon·2022년 9월 24일
0

React

목록 보기
14/23
post-thumbnail

useReducer

이것은 useState의 확장판이라고 보면 된다고 합니다.

  • 다수의 하윗값을 포함하는 복잡한 정적 로직을 만드는 경우
  • 다음 state가 state에 의존적인 경우
  • Redux를 안다면 쉽게 사용 가능
const [state,dispatch] = useReducer(reducer,{count:0 }); //첫번째로는 인자를 받고 2번째는 초기값을 원하는 함수를 넘어준다.

reducer 같은 경우에는 기존에 state값을 변경해주는 setState가 아닌 dispatch 함수를 작성해줍니다.

reducer => state를 변경하는 로직이 담겨 있는 함수
dispatch => action 객체를 넣어서 실행
action => 객체이고 필수 프로퍼티로 type을 가진다.

const reducer = () => {
  	
  
	return newState;
}

첫번째 인자로는 state를 받아오고 두번째로는 action 이라는 객체가 들어옵니다.action은 뭔가 조작을 가미하려는 객체를 의미합니다.
아래 function으로 state를 변경하려는 dispatch를 호출해주고 action을 넣어줍니다

여기에서 action의 type은 count의 하나를 올려주는 action을 담아서 보내주는겁니다. setState랑 비슷하죠
type 이름에 PLUS를 적으면 reducer 함수안에 if 문이 들어와서 action 의 type이 PLUS 이면 state의 카운트 수를 1 올려주어라라고 해줍니다.

const reducer = (state,action) => {
	if(action.type === "PLUS"){
    	return{
        	count: state.count + 1
        }
    }
    
	return newState;
}

export default function Example() {
	const [state,dispatch] = useReducer(reducer,{count:0 });
    
    return (
    	<div>
        	<p>You clicked {state.count} time</p>
            <button onClick={click}>Click me</button>
        </div>
    )
    
    function click() {
    	dispatch({type: "PLUS" })
    }
}

0개의 댓글