Selectors and the useSelector hook in Redux
In the previous lessons we wrote product data to the store. How do we get it from the store?
To do this, we need to write a selector function. This function knows how to extract a specific piece of information from the state value stored in the store and helps avoid writing duplicate code as the application grows. This function takes state as input and outputs the required state slice. For example, like this:
const selectValue = state => state.some.value
At the very beginning of the tutorial, it was mentioned that store has a method getState
. And we could easily use it to get the state value:
const value = selectValue(store.getState())
The problem is that our React components can't directly access the store, because it's forbidden to import it into the component file. But we have the ability to get data in the component using the React-Redux hook useSelector
. Plus, with this hook, our components will always get only relevant data:
const count = useSelector(selectValue)