When I was beginner in using Redux to manage state in JavaScript while using React, I often dispatched unnecessary amount of actions when I could be done with just one or two. Or when I was loading initial data when user visits website, I often dispatched an action that set only specific resource. Something like this:
const fetchAppData = () => dispatch => apiClient.fetchAppData() .then(res => res.json()) .then(res => { if (res.error) { dispatch(actions.showNotification(res, false)) return } dispatch(actions.setUser(res.users)) // action type is SET_USER dispatch(actions.setPosts(res.posts)) // action type is SET_POSTS })
I eventually figured it out Redux store can handle one action in multiple reducers at the same time so the two dispatch lines became one dispatch(actions.setAppData(res))
. Action type is SET_APP_DATA
and is defined as case in both reducers as opposed to SET_USER
which is defined only in users reducer and SET_POSTS
only in posts reducer.
Another use case when you can reduce amount of dispatched actions is when you set a data and at the same time you want to display a notification. Following the previous example we could have another reducer for notifications that sets state of notification to {type:'SUCCESS', message: 'Data loaded'}
when SET_APP_DATA
is dispatched.