For redux itself, you can only dispatch action which is a plain JS object(or an action creator returns an action, this action is a plain JS object must have a type field.). But with various middlewares, you can dispatch various things such as a thunk, plain JS object action, etc. The middleware will transform the action to plain JS object action in the end.
When using the redux-thunk middleware, you can dispatch a thunk like this:
const thunkFunction = (dispatch, getState) => {
// logic here that can dispatch actions or read state
}
store.dispatch(thunkFunction)
The login thunk action creator does return a thunk.
A thunk action creator is a function that may have some arguments, and returns a new thunk function. See Writing Thunks
Another example, redux-promise-middleware,
Given a single action with an async payload, the middleware transforms the action to separate pending action and a separate fulfilled/rejected action, representing the states of the async action.
You can dispatch an action with async payload:
const response = dispatch({
type: 'FIRST',
payload: new Promise(...),
});
Answer from Lin Du on Stack OverflowWhat are some alternatives to useDispatch?
How can I improve performance with useDispatch?
What is selective dispatching?
Videos
I wanted to know why const dispatch = useDispatch() is used, or const history = useHistory()
That's just the way those hooks are designed. The job of these hooks is "please give me the dispatch function" and "please give me the history object" respectively. It's a way of getting a dependency into your component without passing it in as a prop. So all these hooks do is return that piece of data, and then your component can use it from there as it sees fit.
The useSelector hook is a hook which makes it possible to access the Redux store in function component. You can pass a function to the useSelector to access the correct values from your store. Lets say your store looks something likes this:
{ auth:
{ user:
{firstName, lastName }
}
}
If you would like to access the firstName of a user in your function component you can use the useSelector function like this:
const firstName = useSelector(state => state.auth.user.firstName);
I'm trying to refactor an app's state to use redux toolkit. Something I'm frustrated by is how `useDispatch` needs to be imported into every component along with the actions. Does it make sense to make a `useAppHandlers` hook that returns all the prepared handlers?
More context here:
https://stackoverflow.com/questions/68506544/is-this-a-dumb-idea-for-how-to-simplify-redux-react