단순 코드 기록/RE: React

redux toolkit 기초

일일일코_장민기 2024. 5. 23. 08:35
728x90

App.js

더보기
import React from "react";
import { Provider, useDispatch, useSelector } from "react-redux";
import counterSlice from "./counterSlice.js";
import store from "./store.js";

// const initialState = {value:0};
// const reducer = (state, action) =>{
//     if(action.type==="up"){
//         return{...state, value:state.value + action.step}
//     }
//     return state;
// }
// const store = createStore(reducer, initialState);
// createStore(reducer);


// export default function App(){
//     return(
//         <div>
//             <Provider store={store}>
//                 <Counter></Counter>
//             </Provider>
//         </div>
//     );
// }

// const Counter = () =>{
//     const dispatch = useDispatch();
//     const count = useSelector((state) => state.value)
//     return(
//         <div>
//             <button onClick={() => {dispatch({type:'up', step:2})}}>+</button>{count}
//         </div>
//     );
// }

export default function App(){
    return(
        <Provider store={store}>
            <div>
                <Counter></Counter>
            </div>
        </Provider>
       
    )
}

function Counter(){
    const dispatch = useDispatch();
    const count  = useSelector((state) => {
        console.log("state: ", state);
        return state.counter.value});           //state 중 counter reducer의 state(store 기준)
                                                //counter는 counterSlice.reducer이기 떄문에 counterSlice의 value 출력
        return(
        <div>
            <button onClick={() => {
                // dispatch({type: 'counterSlice/up', step: 2}) //type은 counterSlice라고 name이 붙은 slice
                //                                              //해당 slice의 reducers 중 up이라고 이름 붙은 함수
                dispatch(counterSlice.actions.up(2))            //type은 counterSlice/up
                                                                //--> 자동으로 counterSlice라고 name이 붙은 slice의 up 함수 사용
                                                                //2는 payload라는 이름으로 전달
            }}>+</button>{count}
        </div>
    )
}


store.js

더보기
import { configureStore } from "@reduxjs/toolkit";
import counterSlice from "./counterSlice";

const store = configureStore({
    reducer:{
        counter:counterSlice.reducer,
    }
})

export default store;

counterSlice.js

더보기
import { createSlice } from "@reduxjs/toolkit";

const counterSlice = createSlice({
    name:'counterSlice',
    initialState:{value:0},                 //초기값은 0
    reducers:{
        up: (state, action) => {
            console.log("action: ", action)
            //state.value += action.step;
            state.value += action.payload;
        }
    }
});

export default counterSlice;

 

1. redux toolkit
- 설정할 것을 줄여줌
- 반복적으로 작성하는 코드를 줄여줌
- 불변성 유지 용이

================================================================

2. 기존 redux
import React from "react";
import { Provider, useDispatch, useSelector } from "react-redux";
import { createStore } from "redux";

const initialState = {value:0};
const reducer = (state, action) =>{
    if(action.type==="up"){
        return{...state, value:state.value + action.step}
    }
    return state;
}
const store = createStore(reducer, initialState);
createStore(reducer);


export default function App(){
    return(
        <div>
            <Provider store={store}>
                <Counter></Counter>
            </Provider>
        </div>
    );
}

const Counter = () =>{
    const dispatch = useDispatch();
    const count = useSelector((state) => state.value)
    return(
        <div>
            <button onClick={() => {dispatch({type:'up', step:2})}}>+</button>{count}
        </div>
    );
}


####################################
const initialState = {value:0};
// 초기값 지정

const reducer = (state, action) =>{
    if(action.type==="up"){
        return{...state, value:state.value + action.step}
    }
    return state;
}
// useSelect와 useDispatch 사용 시 사용할 함수 설정

const store = createStore(reducer, initialState);
createStore(reducer);
// useSelect와 useDispatch 사용 시 사용할 함수와 초기값 지정

<Provider store={store}>
    <Counter></Counter>
</Provider>
//Provider 설정

####################################
const dispatch = useDispatch();
//useDispatch 설정

const count = useSelector((state) => state.value)
//useSelector 설정

<button onClick={() => {dispatch({type:'up', step:2})}}>+</button>{count}
//dispatch: 액션 설정

================================================================

2. 리덕스 툴킷 도입
npx create-react-app my-app --template redux
npm install @reduxjs/toolkit
slice: store 안의 store

import { createSlice } from "@reduxjs/toolkit";
const counterSlice = createSlice({
    name:'counterSlice',
    initialState:{value:0},
    reducers:{
        up: (state, action) => {
            state.value += action.step;
        }
    }
});
- counterSlice라는 이름의 small store 작성
- initialState로 초기값 지정
- reducers(복수형)을 통해 액션들 설정

================================================================

3. 리덕스 툴킷 효과

up: (state, action) => {}
==> const reducer = (state, action) =>{
        if(action.type==="up"){
        }
        return state;
    }
- 툴킷을 통해 같은 역할


state.value += action.step;
==> return{...state, value:state.value + action.step}
- 툴킷을 통해 같은 역할


================================================================

4. store 작성
- slice를 모아서 store로 작성
import { createSlice, configureStore } from "@reduxjs/toolkit";
const store = configureStore({
    reducer:{
        counter:counterSlice.reducer,
    }
})

<Provider store={store}>
    <div>
        <Counter></Counter>
    </div>
</Provider>

reducer: {
    슬라이스 이름:  슬라이스 상수.reducer
}

================================================================

5. Counter 작성
function Counter(){
    const dispatch = useDispatch();
    const count  = useSelector((state) => {
        console.log("state: ", state); 
        return state.counter.value});                           //state 중 counter reducer의 state(store 기준)
                                                                //counter는 counterSlice.reducer이기 떄문에 counterSlice의 value 출력
    return(
        <div>
            <button onClick={() => {
                // dispatch({type: 'counterSlice/up', step: 2}) //type은 counterSlice라고 name이 붙은 slice
                //                                              //해당 slice의 reducers 중 up이라고 이름 붙은 함수
                dispatch(counterSlice.actions.up(2))            //type은 counterSlice/up
                                                                //--> 자동으로 counterSlice라고 name이 붙은 slice의 up 함수 사용
                                                                //2는 payload라는 이름으로 전달
            }}>+</button>{count}
        </div>
    )
}

================================================================

6. js 분할

//App.js    =====================================
import React from "react";
import { Provider, useDispatch, useSelector } from "react-redux";
import counterSlice from "./counterSlice.js";       //분할
import store from "./store.js";                     //분할

export default function App(){
    return(
        <Provider store={store}>
            <div>
                <Counter></Counter>
            </div>
        </Provider>
        
    )
}

function Counter(){
    const dispatch = useDispatch();
    const count  = useSelector((state) => {
        console.log("state: ", state); 
        return state.counter.value});           //state 중 counter reducer의 state(store 기준)
                                                //counter는 counterSlice.reducer이기 떄문에 counterSlice의 value 출력
        return(
        <div>
            <button onClick={() => {
                // dispatch({type: 'counterSlice/up', step: 2}) //type은 counterSlice라고 name이 붙은 slice
                //                                              //해당 slice의 reducers 중 up이라고 이름 붙은 함수
                dispatch(counterSlice.actions.up(2))            //type은 counterSlice/up
                                                                //--> 자동으로 counterSlice라고 name이 붙은 slice의 up 함수 사용
                                                                //2는 payload라는 이름으로 전달
            }}>+</button>{count}
        </div>
    )
}

//Store.js  =====================================
import { configureStore } from "@reduxjs/toolkit";
import counterSlice from "./counterSlice";

const store = configureStore({
    reducer:{
        counter:counterSlice.reducer,
    }
})

export default store;


//CounterSlice.js =====================================
import { createSlice } from "@reduxjs/toolkit";

const counterSlice = createSlice({
    name:'counterSlice',
    initialState:{value:0},                 //초기값은 0
    reducers:{
        up: (state, action) => {
            console.log("action: ", action)
            //state.value += action.step;
            state.value += action.payload;
        }
    }
});

export default counterSlice;

 

 

 

 

 

'단순 코드 기록 > RE: React' 카테고리의 다른 글

redux 기초  (0) 2024.05.22
Context Api 기초  (0) 2024.05.22
Styled Components 기초  (0) 2024.05.22
Router 기초  (0) 2024.05.21
React 기초  (0) 2024.05.20