Reputation: 55
I followed the react-redux tutorial and the following pattern regularly appears in the example code:
import { useDispatch} from 'react-redux'
...
const dispatch = useDispatch()
https://redux.js.org/tutorials/essentials/part-3-data-flow#adding-new-posts
What is the purpose of redeclaring the dispatch function like this?
I looked at the react-redux code and (I think?) the hook factory returns a function. So is the purpose of redeclaring the dispatch hook to use it as a function expression instead of a function declaration for performance?
Why is this not done for the useSelector
hook?
Upvotes: 2
Views: 5400
Reputation: 85032
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.
Upvotes: 2
Reputation: 734
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);
Upvotes: 0