Do you need action creators when working with Redux hooks?
Answer a question
This is an odd question, but I haven't been able to find an explicit answer for it. In my project I'm using Redux with new Redux hooks, useSelector and useDispatch. The setup is as standard as it gets:
Reducer:
const reducer = (state = defaultState, action) => {
switch (action.type) {
type SOME_ACTION:
return {
...state,
someVariable: action.payload
}
default:
return state
}
Synchronous actions:
export function someAction(payload) {
return {
type: SOME_ACTION
payload: payload
}
And in the components I dispatch actions using dispatch({type: SOME_ACTION, payload: payload})
.
Recently I've noticed that dispatching works just fine even if the action creator doesn't exist: as in, if the SOME_ACTION type is listed in the reducer switch operator, but there is no function someAction(payload). The question is: is writing the action creators redundant in this case? What are the best practices when working with Redux hooks?
Answers
You can certainly use action object literals
dispatch({ type: 'MY_SUPER_AWESOME_ACTION });
But creating action creators allow you to reuse code more efficiently.
const mySuperAwesomeAction = () => ({ type: 'MY_SUPER_AWESOME_ACTION });
And now anywhere in your app where you need to dispatch this action you import the action and use
dispatch(mySuperAwesomeAction());
As apps grow and actions are used in multiple components if you were using object literals you would need to find/replace all instances of the action literal, and hope you didn't typo any of them. With the single action creator definition you need only update it in a single location.
更多推荐
所有评论(0)