티스토리 뷰

Redux-Toolkit 초기 설정

리액트 네이티브에서 Redux-Toolkit 초기 설정 하는 방법을 알아보겠습니다.


Redux-Toolkit 설치

npm

npm install @reduxjs/toolkit react-redux

yarn

yarn add @reduxjs/toolkit react-redux

 


폴더구조

폴더 구조는 사람마다 각 기 다른 방식으로 이루어집니다.


초기 설정 시작

Redux Slice 만들기

// src/redux/slices/countrySlice.js
import { createSlice } from '@reduxjs/toolkit';

const initialState = {
  countryImg: null,
  countryName: null,
  cityName: null,
};

const countrySlice = createSlice({
  name: 'country',
  initialState,
  reducers: {
    setCountryInfo: (state, action) => {
      state.countryImg = action.payload.countryImg;
      state.countryName = action.payload.countryName;
      state.cityName = action.payload.cityName;
    },
  },
});

export const { setCountryInfo } = countrySlice.actions;
export default countrySlice.reducer;

Redux Store 만들기

// src/redux/store.js
import { configureStore } from '@reduxjs/toolkit';
import countryReducer from './countrySlice';

const store = configureStore({
  reducer: {
    country: countryReducer,
  },
});

export default store;

Provider로 App 컴포넌트 래핑 & App 컴포넌트 안에 요소들을 래핑 해도 됩니다.

import store from './redux/store/store';
import {Provider} from 'react-redux';

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

사용 방법

useDispatch (상태 업데이트)

useDispatch를 사용하여 상태를 업데이트합니다.

import React from 'react';
import { Button } from 'react-native';
import { useDispatch } from 'react-redux';
import { setCountryInfo } from './countrySlice';

const CountryButton = () => {
  const dispatch = useDispatch();

  const handlePress = () => {
  // 상태 업데이트
    dispatch(setCountryInfo({
      countryImg: 'URL_TO_COUNTRY_IMAGE',
      countryName: 'USA',
      cityName: 'New York', 
    }));
  };

  return (
    <Button title="Set Country" onPress={handlePress} />
  );
};

export default CountryButton;

useSelector (상태 값 가져오기)

useSelector를 사용하여 상태 값을 가져옵니다.

import React from 'react';
import { Text, View } from 'react-native';
import { useSelector } from 'react-redux';

const CountryInfo = () => {
// 상태 값 가져오기
  const countryImg = useSelector((state) => state.country.countryImg);
  const countryName = useSelector((state) => state.country.countryName);
  const cityName = useSelector((state) => state.country.cityName);

  return (
    <View>
      {countryName ? (
        <Text>
          Country Image URL: {countryImg} 
          Country Name: {countryName}
          City Name: {cityName}
        </Text>
      ) : (
        <Text>No country information set yet</Text>
      )}
    </View>
  );
};

export default CountryInfo;
댓글
«   2025/05   »
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 31
공지사항