dev/React Native

Redux Toolkit과 Redux Logger를 활용한 React Native 상태 관리 가이드 (1부)

wndud587 2024. 11. 28. 15:53
728x90

 

이 글에서는 React Native 애플리케이션에서 Redux ToolkitRedux Logger를 사용하여 효율적으로 상태 관리를 설정하고 사용하는 방법을 단계별로 안내합니다.

 


 

 

1. Redux Toolkit 및 Logger 설치

 

Redux Toolkit은 Redux 설정 과정을 간소화하고 유지보수를 쉽게 해주는 라이브러리입니다.
Redux Logger는 상태 변화 로그를 기록하여 디버깅에 도움을 줍니다.

다음 명령어로 두 라이브러리를 설치합니다.

yarn add react-redux @reduxjs/toolkit
yarn add redux-logger

 

 

2. 프로젝트 폴더 구조

아래와 같은 폴더 구조를 생성합니다.

src/
└── stores/
    ├── index.js          # 스토어 설정 파일
    ├── reducers.js       # 리듀서 결합 파일
    └── slices/           # Slice 파일 폴더
        └── sampleSlice.js

 

 

3. store 설정

/stores/index.js 파일을 생성하여 Redux 스토어를 설정합니다. Redux Logger를 미들웨어로 추가해 상태 변화를 콘솔에 기록합니다.

 

// /stores/index.js
import {configureStore} from '@reduxjs/toolkit';
import rootReducer from './reducers';
import logger from 'redux-logger';

const store = configureStore({
  reducer: rootReducer, // 여러 리듀서를 결합한 rootReducer 사용
  middleware: getDefaultMiddleware => getDefaultMiddleware().concat(logger),
});

export default store;

 

 

4. reducer 설정

리듀서를 결합하기 위해 /stores/reducers.js를 생성합니다.

// /stores/reducers.js
import {combineReducers} from '@reduxjs/toolkit';
import samplesSlice from './slices/sampleSlice';

const rootReducer = combineReducers({
  samples: samplesSlice, // sampleSlice를 등록
});

export default rootReducer;

 

 

5. slice 생성

slice는 상태와 액션을 하나로 결합한 개념으로, Redux Toolkit의 createSlice를 사용해 간단히 생성할 수 있습니다.

아래는 /stores/slices/sampleSlice.js에 작성한 slice 예제입니다.

import {createSlice} from '@reduxjs/toolkit';
//  init
const initialState = {
  isAuth: false,
  isLoading: true,
};

const samplesSlice = createSlice({
  name: 'sample',
  initialState: initialState,
  reducers: {
    login: state => {
      return {
        ...state,
        isAuth: true,
      };
    },
    logout: state => {
      return {
        ...state,
        isAuth: false,
      };
    },
    setLoading: (state, action) => {
      const {isLoading} = action.payload;
      return {
        ...state,
        isLoading: isLoading,
      };
    },
  },
});

const {reducer, actions} = samplesSlice;

//

export const {login, logout, setLoading} = actions;

export default reducer;

 

 

6. 컴포넌트에서 상태 사용하기

React Native 컴포넌트에서 Redux 상태와 액션을 사용하는 방법을 소개합니다.

import React, {useEffect} from 'react';
import {View, Text, Button} from 'react-native';

import {Provider, useDispatch, useSelector} from 'react-redux';
import store from './src/stores';
import {login, setLoading} from './src/stores/slices/sampleSlice';
import BootSplash from 'react-native-bootsplash';

const Sample = () => {
  const dispatch = useDispatch();
  const {isLoading} = useSelector(state => state.samples);

  useEffect(() => {
    const init = async () => {};

    init().finally(async () => {
      await BootSplash.hide({fade: true});
    });
  }, []);

  return (
    <View>
      <Text>{`loading? ${isLoading}`}</Text>
      <Button
        onPress={() => {
          dispatch(setLoading({isLoading: !isLoading}));
        }}
        title="버튼"
      />
    </View>
  );
};

const App = () => {
  return (
    <Provider store={store}>
      <Sample />
    </Provider>
  );
};

export default App;

 

  • useSelector: Redux 상태에서 samples의 slice 중 구조분해 할당으로 isLoading 값을 가져옵니다.
  • useDispatch: setLoading 액션을 디스패치하여 상태를 변경합니다.
  • Redux Logger를 통해 상태 변화가 콘솔에 출력됩니다.

 

 

redux 초기 상태값
기본값 true

 

 

 

액션을 디스패치하여 상태를 변경
버튼을 누르면 isLoading의 반대값으로 수정


 

 

 

* 이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다.

728x90