Redux
상태관리 라이브러리
예측 가능한 상태 컨테이너 제공
store에 상태를 넣어두고 필요한 컴포넌트에서 가져다 사용
설치
npm i redux --save
사용이유
store에서 모든 state를 관리하고 있고, action을 dispatch해야 reducer가 state를 업데이트
-> 그 후 해당 state를 구독하는 컴포넌트들이 선택적으로 리렌더링
Action
{ type: 'LIKE_ARTICLE', articleId: 42 }
{ type: 'FETCH_USER_SUCCESS', response: { id: 3, name: 'Mary' } }
{ type: 'ADD_TODO', text: 'Read the Redux docs.' }
Reducer
const counter = (state = 0, action: { type: string }) => {
switch (action.type) {
case "INCREMENT":
return state + 1;
case "DECREMENT":
return state - 1;
default:
return state;
}
}
import React from 'react'
import { combineReducers } from 'redux';
import counter from './counter';
import todos from './todos';
import posts from './posts';
const rootReducer = combineReducers({
counter,
todos,
posts
});
export default rootReducer;
export type RootState = ReturnType<typeof rootReducer>;
Store
import { createStore, } from 'redux';
import counter from './reducers/counter';
const store = createStore(counter);
Redux로 상태관리
getState()
dispatch()
const render = () => root.render(
<React.StrictMode>
<App
value={store.getState()}
onIncrement={() => store.dispatch({ type: 'INCREMENT' })}
onDecrement={() => store.dispatch({ type: 'DECREMENT' })}
/>
</React.StrictMode>
);
subscribe()
store.subscribe(render);
React-Redux
npm i react-redux --save
Provider
import { Provider } from 'react-redux';
const render = () => root.render(
<React.StrictMode>
<Provider store={store}>
<App
value={store.getState()}
onIncrement={() => store.dispatch({ type: 'INCREMENT' })}
onDecrement={() => store.dispatch({ type: 'DECREMENT' })}
/>
</Provider>
</React.StrictMode>
);
useSelector()
import { useSelector } from 'react-redux';
const todos: string[] = useSelector((state: RootState) => state.todos);
const counter = useSelector((state: RootState) => state.counter);
const posts: Post[] = useSelector((state: RootState) => state.posts);
useDispatch()
import { useDispatch } from 'react-reduxs';
const dispatch = useDispatch();
dispatch(...수행할 action...);