여러 채용 공고를 보면 필수 기술 스택에 상태 관리 라이브러리가 적혀있는 게 많다
상태 관리 라이브러리를 요구하는 곳은 특히 redux가 많다
실무에서 써보긴 했지만 오래 됐기도 했고 Toolkit이 나오고 마이그레이션 작업을 내가 안 해서 잘 모른다,,,
참고
애플리케이션의 상태를 관리하는 라이브러리
const exampleAction = {
type: '<<type>>',
payload: '<<session>>'
}
const initialState = { value: '' }
const exampleReducer = (state = initialState, action) => {
if(action.type === '<<type1>>'){
return {...state, count: state.count + 1 }
}else if (action.type === '<<type2>>'){
//...
}
return state
}
이름이 reducer인 이유
const result = Array.reducer((previousResult, currentItem)=>{
//...
return //..
}, initialValue)
// store 생성
import { configureStore } from '@reduxjs/toolkit'
const store = configureStore({ reducer: exampleReducer })
console.log(store.getState())
// {value: 0}
store객체에 있는 dispatch 메서드를 사용해 업데이트dispatch 메서드 인수로 액션 객체를 넣어 원하는 동작을 하도록 함dispatch와 action을 이용하는 방법으로만 상태 업데이트가 가능함store.dispatch(exampleAction)
// action에 정의된 타입으로
// reducer에서 정의한 동작으로
// 상태가 변경되어 저장됨
return (
<div>
<Provider store={exampleStore}>
<Input />
</Provider>
<Button />
</div>
)
Input 컴포넌트에서는 exampleStore 객체에 접근 가능Button 컴포넌트는 provider의 자식이 아니기 때문에 exampleStore 객체에 접근 불가리액트 프로젝트를 이제 시작할 예정인데 작은 규모라도 일부러라도 전역상태 관리 라이브러리를 사용할 예정이다! 다음 글에서는 로그인 세션저장을 리덕스로 구현하여 기존에 리덕스 없이 세션 저장한 로직과 비교할 예정이다