I am learning about react + redux. I have 3 questions related to it.
query-1: The ways to access a store inside a component. According to the official documentation here there are 2 ways
- hooks(useSelector etc.)
- connect.
By importing store in our component we can access the store via store.getState() or store.dispatch()
So aren't there 3 ways?
query-2:. We use thunk so that we can do async operations in our action creator(eg API call). The action creator can return a function (instead of an action). Here is a simple example.
const fetchUser = (data) => {
return (dispatch) => {
axios.post('url', data).then(() => { dispatch(action) }).catch();
}
}
And we can now dispatch fetchUser from our component(eg: dispatch(fetchUser(payload)) )
Why cannot we simply pass dispatch function to fetchUser instead of using thunk, Here is an example
const dispatch = useDispatch();
fetchUser(payload, dispatch)`
Asking because it worked perfectly fine.
query-3: While creating a redux store, we pass 3 parameters, 1. reducer 2. [preLoadedState] 3. [enhancers]. I have mostly seen examples as shown below
const store = createStore(rootReducer, applyMiddleware(thunk))
OR
const store = createStore(rootReducer, compose(applyMiddleware(thunk)))
Since applymiddleware is a store enhancer, we can see we have skipped second parameter. Any thoughts on this?
Q1
As you rightly pointed out there are 2 ways to get Redux State:
useSelector)connectstore.dispatchoruseDispatchis not accessing the Redux State.Instead it is allowing you to mutate the state of the Store by dispatching actions.
Think of it as:
useSelectorandconnectare subscribers to the Store (they blindly accept changes from the Store)useDispatchandstore.Dispatchare prescribers to the Store (actions tell the Store what is changing, and what it's new value will be)Q2
You can pass the
dispatchobject around, there's nothing wrong with that (per se), but it could become unclear as to what that object is. In both examples you use, it shows thedispatchobject being used to call an action.Thunk is just used to handle that async behaviour so you don't have to (so much)
Q3
The reason why
applymiddlewareis called, is because you are then able to pass multiple things into your ReduxStoreFor example: