Redux Toolkit

Jinmin Kim·2021년 12월 6일
0

Toolkit 정리

configureStore()

redux devtools를 사용할수있게 자동으로 등록해준다.

const store = configureStore({ reducer });

createAction()

createAction은 긴 action code를 간단하게 사용할수있게해주는 방법
console.log를 찍었을경우에 {type : , payload: }의 형식으로 데이터가 나타난다.

//action 
const ADD = "ADD";
const DELETE = "DELETE";

const addToDo = text => {
    return {
        type: ADD,
        text
    };
};

const deleteToDo = id => {
    return {
        type: DELETE,
        id: parseInt(id)
    };
};
//--------------------------------------------------------------
//1. redux toolkit createAction을 실행시키면 가 나타난다.
const addToDo = createAction("ADD");
const deleteToDo = createAction("DELETE");

createReducer()

  1. mutate 가능(immer.js가 내부적으로 기능 진행)
  2. 새로운 객체 return도 가능
//reducer 
const reducer = (state = [], action) => {
    switch(action.type){
        // case ADD:
        case addToDo.type:
            // return [{text: action.text, id: Date.now()}, ...state];
            return [{text: action.payload, id: Date.now()}, ...state];
        // case DELETE:
        case deleteToDo.type:
            // return state.filter(toDo => toDo.id !== action.id)
            return state.filter(toDo => toDo.id !== action.payload)
        default:
            return state;
    }
}
//--------------------------------------------------------------

//2. redux toolkit createReducer을 실행시키면 {type : , payload: }가 나타난다.

const reducer = createReducer([], {
    [addToDo] : (state, action) => {
        //mutate 가능!!!**
        state.push({text: action.payload, id: Date.now()});
    },
    [deleteToDo]: (state, action) => state.filter(toDo => toDo.id !== action.payload)
        
})

createSlice()

createAction + createReducer의 기능을 가지고 두가지를 한꺼번에 만들수있다.
createSlice는 redux 에서 모듈을 관리하기 위한 패턴중 ducks-pattern 을 공식적으로 지원하기 위해 나왔다. 가장 눈에띄는 부분으로는 reducer 만 생성하여도 reducer의 key 값으로 액션까지 자동으로 생성해 주는 기능을 지원한다.

const toDos = createSlice({
    name: "toDoReducer",
    initialState: [],
    reducers: {
        add: (state, action) => {
            state.push({text: action.payload, id: Date.now()});
        },
        remove: (state,action) => state.filter(toDo => toDo.id !== action.payload)
    },
    /**extraReducers 는 액션을 자동으로 생성해 주지 않기때문에 별도의 
    액션이 존재하는 함수의 reducer를 정의할 경우에 사용합니다.*/
    extraReducers: { 
      [change]: (state, action) => {
        return state.content + action.payload
    }
}) 

//toDos.reducer => reducer
const store = configureStore({ reducer: toDos.reducer });

//toDos.action => action
export const {add, remove} = toDos.actions;

export default store;

createSelector()

createSelector 함수가 즉 이전에 계산한 값을 메모리에 저장하여 값이 변경됐을 경우에만 계산하도록 동작하게된다.

const shopItemsSelector = state => state.shop.items

const subtotalSelector = createSelector(
  shopItemsSelector,
  items => items.reduce((subtotal, item) => subtotal + item.value, 0)
)

createAsyncThunk()

react-redux

useDispatch()

redux의 있는 dispatch를 가져다가 사용할수있다

const dispatch = useDispatch();

useSelector()

const todos = useSelector(state => state.todos);

useSelector를 사용해서 리덕스 스토어의 상태를 조회 할 땐 만약 상태가 바뀌지 않았으면 리렌더링하지 않는다

profile
Let's do it developer

0개의 댓글