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?