<aside> <img src="https://s3-us-west-2.amazonaws.com/secure.notion-static.com/f765100f-b481-437e-b531-5aae8d9bc5fe/1200px-React-icon.svg.png" alt="https://s3-us-west-2.amazonaws.com/secure.notion-static.com/f765100f-b481-437e-b531-5aae8d9bc5fe/1200px-React-icon.svg.png" width="40px" /> Velopert's Modern React
</aside>
목차
useReducer와 useState의 차이
useReducer 라는 Hook 함수를 이해하기 전에, 상태를 관리하는 방식에 대해서 정리해보자.
React Hook에서 도입된 useState로 우리는 함수형 컴포넌트 안에서 state를 관리할 수 있게 되었다. const [ users, setUsers ] = useState( { state 기본값} )
바로 이런 식으로 말이다.
이 방식으로 state를 관리하려면 무조건 컴포넌트 안에 state를 정의하는 useState 로직이 있어야 한다. 이번에 기록하는 useReducer 함수는 useState와는 다르게, 컴포넌트 밖에서 state를 관리할 수 있게 만들고, 심지어는 다른 파일에 작성한 state를 불러와서 사용할 수 있게 해준다. 가보자. 🚀
(배열 메서드 reduce와는 다르다. I Love .reudce
)
reducer 함수
현재 상태와 액션 객체를 파라미터로 받아서 새로운 state를 반환해주는 함수다. 한마디로 reducer 함수가 발동되면 컴포넌트가 지니는 state의 상태가 변경되고, 새로운 state를 지니게 된다는 말이다.
reducer 함수
function reducer(state, action) {
// 새로운 상태를 만드는 로직
// const nextState = ...
return nextState;
}