티스토리 뷰

Front-end/Redux

Redux Toolkit

ekki88 2025. 3. 19. 11:44

Redux의 역할

프로젝트 내 전역 상태 관리

사용 중인 패턴

  • Redux Toolkit을 사용한 slice 기반 상태 관리 (createSlice 사용)
  • Ducks 패턴을 따르며, 한 파일에 state, reducers, actions 포함

redux 사용 시

1️⃣ 스토어 작성

2️⃣ provider적용

3️⃣ slice에서 액션, 리듀서 정의 : createSlice 사용해서 redux상태,액션을 한번에 정의

4️⃣ selector 함수 생성 : redux상태를 가져오는 로직을 분리해 재 사용할 수 있도록 도와줌

5️⃣ 컴포넌트에서 useAppSelector로 상태 가져오거나 useDispatch 사용해 상태 변경하며 사용한다

 

store

configureStore : redux 스토어를 쉽게 설정

const store = configureStore({
  reducer: rootReducer,
  middleware: (getDefaultMiddleware) => getDefaultMiddleware({
    serializableCheck: false, // 직렬화 검사 
    actionCreatorCheck: false, // 커스텀 액션 로직 사용시 비활성화 
    thunk: true, // redux-thunk를 활성화할지 여부
    immutableCheck: false, //불변성 검사
  }),
  devTools: false,
});
  • serializableCheck : redux상태나 액션이 직렬화 할 수 없는 값
  • 직렬화: 데이터를 저장하거나 전송할 수 있는 형식으로 변환하는 과정
  • actionCreatorCheck : 올바른 redux액션인지 검사, 비정상적인 액션 디스패치 방지
  • immutableCheck : 리덕스 상태가 불변성을 유지하는지 검사
const rootReducer = combineReducers({
  workspace: workspaceSlice,
  project: projectSlice,
  facility: facilitySlice,
  diagnosis: diagnosisSlice,
  viewer: viewerSlice,
  dxfViewer: dxfViewerSlice,
});

combineReducers : 여러 개의 리듀서를 관리해줌

workspace: 작업

project: 프로젝트

facility: 시설물

diagnosis: 진단

viewer: photo viewer 영역

dxfViewer: dxf viewer 영역

 

Slice

createSlice : reducer, action 한 번에 생성

const workspaceAdapter = createEntityAdapter<NormalizedWorkspacesDTO, string>({
  selectId: (workspace) => workspace.jobFolderId,
});
  • createEntityAdapter : 배열 데이터를 쉽게 관리하도록 하는 기능
export interface WorkspaceEntityState
  extends EntityState<NormalizedWorkspacesDTO, string> {
  current: NormalizedWorkspacesDTO | null;
  currentId: string | null;
}

export interface WorkspaceState {
  entities: {
    workspace: WorkspaceEntityState;
  };
  loading: "idle" | "pending" | "succeeded" | "failed";
  error: string | null;
}

const initialState: WorkspaceState = {
  entities: {
    workspace: workspaceAdapter.getInitialState({
      current: null,
      currentId: null,
    }),
  },
  loading: "idle",
  error: null,
};

타입, 기본 값 지정

const workspaceSlice = createSlice({
  name: "workspace",
  initialState,
  reducers: {
  ''
  },
  extraReducers: (builder) => {
  ''
  },
});

export const { increment, decrement } = workspaceSlice.actions;
  • action : 상태를 어떻게 변경할지 명령하는 객체
  • reducer : 현재 상태와 액션을 받아 새로운 상태를 반환하는 함수
  • extraReducers : 비동기 액션 (createAsyncThunk로 생성된 액션) 또는 다른 슬라이스의 액션 처리 가능

Selector

export const selectWorkspaceState = (state: RootState) => state.workspace;

상태를 가져와서 편리하게 사용할 수 있게 작성해줌

 

redux toolkit 상태 변경 흐름

1️⃣사용자가 액션을 발생 (버튼 클릭, 입력 등)

2️⃣ 컴포넌트에서 dispatch(action) 실행

3️⃣ 스토어(Store)가 액션을 리듀서에 전달

4️⃣ 리듀서(Reducer)가 새로운 상태를 생성하고 반환

5️⃣ 스토어가 변경된 상태를 저장

6️⃣ 구독 중인 컴포넌트(useAppSelector)가 변경을 감지하고 리렌더링됨

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
글 보관함