Redux-Actions
yarn add redux-actions
import { createAction, handleActions } from "redux-actions"
//액션 함수
const INCREASE = "counter/INCREASE"
const DECREASE = "counter/DECREASE"
export const increase = createAction(INCREASE)
export const decrease = createAction(DECREASE)
//리듀서
const initialState = {
number: 0,
}
const counter = handleActions(
{
[INCREASE]: (state, action) => ({ number: state.number + 1 }),
[DECREASE]: (state, action) => ({ number: state.number - 1 }),
},
initialState
)
export default counter
Action 함수를 createAction 함수를 사용하여 만들어준다.
Reducer 함수를 간단하고 가독성높게 handleActions 함수를 사용하여 만든다.
useSelector 문법 :
const 결과 = useSelector(상태 선택 함수)
- useSelector 함수는 mapStateToProps와 형태가 같음
- useSelector Hooks 를 사용하면 connect 함수를 사용하지 않고 리덕스 상태를 조회 할 수 있음
//react hooks 호출
import React, { useCallback } from "react"
//redux hooks 호출
import { useSelector, useDispatch } from "react-redux"
import Counter from "../components/Counter"
// actions 호출
import { increase, decrease } from "../modules/counter"
const CounterContainer = () => {
const number = useSelector((state) => state.counter.number)
const dispatch = useDispatch()
const onIncrease = useCallback(() => {
dispatch(increase())
}, [dispatch])
const onDecrease = useCallback(() => {
dispatch(decrease())
}, [dispatch])
return <Counter number={number} onIncrease={onIncrease} onDecrease={onDecrease} />
}
export default CounterContainer
useDispatch 문법:
const dispatch =useDispatch() dispatch({type:'SAMPLE ACTION'})
useDispatch 적용:
return ( <Counter number={number} onIncrease={()=>dispatch(increase())} onDecrease={()=>dispatch(decrease())} />
여기서 이렇게 사용하면 컴포넌트가 리렌더링 때마다 onIncrease, onDecrease 함수가 새롭게 만들어지고 있음.
그래서 useCallback 액션을 dispatch 하여 주는것이 좋은 코드 습관임.
const dispatch = useDispatch()
const onIncrease = useCallback(() => {
dispatch(increase())
}, [dispatch])
const onDecrease = useCallback(() => {
dispatch(decrease())
}, [dispatch])
const store=useStore()
store.dispatch({type:'SAMPLE ACTION'})
store.getState()
useStore 컴포넌트는 어쩌다가 스토에 직접 접근해야 하는 상황에만 사용해야 한다고 한다...사용이 흔치 않다고 함..