The screenshot below is taken from the Maximilian Schwarzmüller's Udemy Course "React - The Complete Guide (incl Hooks, React Router, Redux)"
When using useSelector to access some part of the state, it is not obvious where the state is being passed in. In the screenshot below, Max executes useSelector to access the cartIsVisible method of the ui reducer - but how does he get access to the state itself? Since the useSelector is just a hook taken from react-redux and there is nothing else passed in, how does he have access to state? When I tried to console.log(state) it shows an error that state is not defined.
CodePudding user response:
If you look at the index.js you should see a <Provider wrapping the App component as so
<Provider store={store}>
<App />
</Provider>
The useSelector hook gets the state from the redux store sent in the wrapper <Provider component.
The Provider makes the Redux store available to the component hierarchy below.
CodePudding user response:
I'm a Redux maintainer and author of the last couple React-Redux versions.
Internally, useSelector gets access to the Redux store via a useContext hook. It then calls store.subscribe() to be notified any time an action is dispatched, and uses store.getState() to get the latest state. Finally, it calls yourSelector(state).
See my extensive post The History and Implementation of React-Redux and talk ReactNext 2019: A Deep Dive into React-Redux for more details on how React-Redux works internally.
CodePudding user response:
In this case, state is an argument of the useSelector hook. You cannot console.log state because as it belongs to the useSelector hook, I believe it is out of scope in regards to your attempted console.log.
The following is directly from the React Redux documentation on the matter:
The selector is approximately equivalent to the mapStateToProps argument to connect conceptually. The selector will be called with the entire Redux store state as its only argument. The selector will be run whenever the function component renders (unless its reference hasn't changed since a previous render of the component so that a cached result can be returned by the hook without re-running the selector). useSelector() will also subscribe to the Redux store, and run your selector whenever an action is dispatched.

