1. 미들웨어(Middleware) # const customMiddleware = (storeAPI) => (next) => (action) => { /* 해당 Reducer가 실행되기 전에 미들웨어에서 처리할 작업 */ return next(action); // 다음 미들웨어로 이동 } Redux에서 미들웨어는 Store의 dispatch, getState 메서드를 담고 있는 객체 storeAPI, 다음 미들웨어를 가리키는 next, Action 객체인 action을 차례차례로 argument로 받는 커링 함수 형태를 띄고 있음. 특정한 Action이 Dispatch 되고, 해당 Reducer가 실행되기 전 또는 후에 미들웨어가 실행됨. 1. 실행 시점: 해당 Reducer가 실행되기 전 또는 후 2..
1. 비동기 로직 다루기: createAsyncThunk #import { createAsyncThunk } from '@reduxjs/toolkit';export const fetchSearchResults = createAsyncThunk( 'search/setResults', async (payload, thunkAPI) => { /* 비동기 로직 */ });createAsyncThunk()는 type, payloadCreator 두 개의 argument를 받음. ① type: 비동기 Action을 만드는 데 사용할 문자열로, Slice Reducer의 이름 A, Reducer의 이름으로 사용할 B에 대해 "A/B" 형태의 문자열로 작성해주면 됨. 이때, B는 Slice Re..
1. useSelector()로 Derived State를 얻고자 할 때 #useSelector compares its results using strict === reference comparisons, so the component will re-render any time the selector result is a new reference! This means that if you create a new reference in your selector and return it, your component could re-render every time an action has been dispatched, even if the data really isn't different.useSelect()..
import thunkMiddleware from 'redux-thunk' const middlewareEnhancer = applyMiddleware(thunkMiddleware); export default const store = createStore(rootReducer, middlewareEnhancer); Thunk 미들웨어(thunkMiddleware)는 위와 같이 Redux Store에 마운트할 수 있는데, 그 첫 과정으로 thunkMiddleware는 아래와 같은 함수에서 반환됨. 1. redux-thunk에서의 thunkMiddleware # // 'redux-thunk' index.js function createThunkMiddleware(extraArgument) { const m..
1. 컴포넌트에서 Redux Store에 접근하는 방법 import store from './app/store'; import { Provider } from 'react-redux'; ReactDOM.render( , document.getElementById('root') ); 특정 컴포넌트에서 Redux Store에 접근하고자 할 경우 해당 컴포넌트를 Provider 컴포넌트로 감싸야 함. Provider 컴포넌트는 Redux Store를 store 속성으로 가지므로 우리가 구성해준 Store를 전달해주면 됨. 위 코드에서 App 컴포넌트와 그 하위 컴포넌트들은 useSelector(), useDispatch() hook을 통해 우리가 정의한 Redux Store(./app/store.js 파일)에..
1. Thunk Middleware 앞서 Reducer는 Side-effect가 없는 순수함수여야 함을 알았음. 하지만, 네트워크 통신, 데이터 내보내기, setTimeout()와 같은 타이머 등 Side-effect가 없는 애플리케이션은 존재하지 않기 때문에 Redux에서 Side-effect를 다룰 수 있는 방법이 필요함. 이러한 Side-effect를 처리하기 위해 disptach()가 Store에 작업을 전달하기 전에 특수한 일을 할 수 있도록 disptach를 커스텀하는 함수인 Middleware라는 개념이 도입됨. Middleware는 UI 컴포넌트와 Store의 연결 다리 역할을 하기 때문에 Middleware에는 일반 객체가 아닌 값(ex. Promise)이 전달될 수 있고(순수함수일 필요..
1. Redux 기본 개념 A. Redux란? a. 여러 컴포넌트간 공유가 필요한 Global State를 저장하는 하나의 공간 Store가 존재 b. 특정한 이벤트가 발생할 경우, action 객체를 Store에 전달함 c. action을 관찰해 불변성(Immutable)을 유지하도록 State를 업데이트하는 Reducer 함수로 이루어짐 B. Redux의 3가지 원칙 1. Single Source of Truth 어플리케이션의 모든 Global State는 유일한 Store에 하나의 객체 트리 구조로 저장되어야 함. 2. Read-Only State State를 변화시키는 방법은 오직 action 객체를 Store에 전달하는 것뿐이고, 그 외에 State를 변화시키는 방법은 존재하지 않아야 함. 3...
JavaScript/Redux 2022. 9. 16. 17:45
1. 미들웨어(Middleware) # const customMiddleware = (storeAPI) => (next) => (action) => { /* 해당 Reducer가 실행되기 전에 미들웨어에서 처리할 작업 */ return next(action); // 다음 미들웨어로 이동 } Redux에서 미들웨어는 Store의 dispatch, getState 메서드를 담고 있는 객체 storeAPI, 다음 미들웨어를 가리키는 next, Action 객체인 action을 차례차례로 argument로 받는 커링 함수 형태를 띄고 있음. 특정한 Action이 Dispatch 되고, 해당 Reducer가 실행되기 전 또는 후에 미들웨어가 실행됨. 1. 실행 시점: 해당 Reducer가 실행되기 전 또는 후 2..
JavaScript/Redux 2022. 9. 1. 22:44
1. 비동기 로직 다루기: createAsyncThunk #import { createAsyncThunk } from '@reduxjs/toolkit';export const fetchSearchResults = createAsyncThunk( 'search/setResults', async (payload, thunkAPI) => { /* 비동기 로직 */ });createAsyncThunk()는 type, payloadCreator 두 개의 argument를 받음. ① type: 비동기 Action을 만드는 데 사용할 문자열로, Slice Reducer의 이름 A, Reducer의 이름으로 사용할 B에 대해 "A/B" 형태의 문자열로 작성해주면 됨. 이때, B는 Slice Re..
JavaScript/Redux 2022. 9. 1. 22:33
1. useSelector()로 Derived State를 얻고자 할 때 #useSelector compares its results using strict === reference comparisons, so the component will re-render any time the selector result is a new reference! This means that if you create a new reference in your selector and return it, your component could re-render every time an action has been dispatched, even if the data really isn't different.useSelect()..
JavaScript/Redux 2022. 8. 20. 20:13
import thunkMiddleware from 'redux-thunk' const middlewareEnhancer = applyMiddleware(thunkMiddleware); export default const store = createStore(rootReducer, middlewareEnhancer); Thunk 미들웨어(thunkMiddleware)는 위와 같이 Redux Store에 마운트할 수 있는데, 그 첫 과정으로 thunkMiddleware는 아래와 같은 함수에서 반환됨. 1. redux-thunk에서의 thunkMiddleware # // 'redux-thunk' index.js function createThunkMiddleware(extraArgument) { const m..
JavaScript/Redux 2022. 7. 6. 11:04
1. 컴포넌트에서 Redux Store에 접근하는 방법 import store from './app/store'; import { Provider } from 'react-redux'; ReactDOM.render( , document.getElementById('root') ); 특정 컴포넌트에서 Redux Store에 접근하고자 할 경우 해당 컴포넌트를 Provider 컴포넌트로 감싸야 함. Provider 컴포넌트는 Redux Store를 store 속성으로 가지므로 우리가 구성해준 Store를 전달해주면 됨. 위 코드에서 App 컴포넌트와 그 하위 컴포넌트들은 useSelector(), useDispatch() hook을 통해 우리가 정의한 Redux Store(./app/store.js 파일)에..
JavaScript/Redux 2022. 7. 2. 17:27
1. Thunk Middleware 앞서 Reducer는 Side-effect가 없는 순수함수여야 함을 알았음. 하지만, 네트워크 통신, 데이터 내보내기, setTimeout()와 같은 타이머 등 Side-effect가 없는 애플리케이션은 존재하지 않기 때문에 Redux에서 Side-effect를 다룰 수 있는 방법이 필요함. 이러한 Side-effect를 처리하기 위해 disptach()가 Store에 작업을 전달하기 전에 특수한 일을 할 수 있도록 disptach를 커스텀하는 함수인 Middleware라는 개념이 도입됨. Middleware는 UI 컴포넌트와 Store의 연결 다리 역할을 하기 때문에 Middleware에는 일반 객체가 아닌 값(ex. Promise)이 전달될 수 있고(순수함수일 필요..
JavaScript/Redux 2022. 6. 28. 19:47
1. Slice Reducer 구성하기 export default function appReducer(state = initialState, action) { switch (action.type) { // Reducer를 1개만 정의했는데도 코드가 무척 장황함 case 'todos/todoAdded': { return { ...state, todos: [ ...state.todos, { id: nextTodoId(state.todos), text: action.payload, completed: false } ] } } default: return state } } Reducer에 추가하는 로직이 많아지면 ① switch 문에 여러 개의 case를 작성해야 할 뿐만 아니라, Immutable하게 Stat..
JavaScript/Redux 2022. 6. 15. 11:46
1. Redux 기본 개념 A. Redux란? a. 여러 컴포넌트간 공유가 필요한 Global State를 저장하는 하나의 공간 Store가 존재 b. 특정한 이벤트가 발생할 경우, action 객체를 Store에 전달함 c. action을 관찰해 불변성(Immutable)을 유지하도록 State를 업데이트하는 Reducer 함수로 이루어짐 B. Redux의 3가지 원칙 1. Single Source of Truth 어플리케이션의 모든 Global State는 유일한 Store에 하나의 객체 트리 구조로 저장되어야 함. 2. Read-Only State State를 변화시키는 방법은 오직 action 객체를 Store에 전달하는 것뿐이고, 그 외에 State를 변화시키는 방법은 존재하지 않아야 함. 3...