Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where does useSelector Pull State from if it is Not Passed In?

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.

enter image description here

like image 923
brunshte Avatar asked Dec 30 '25 13:12

brunshte


2 Answers

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.

like image 60
Sangeet Agarwal Avatar answered Jan 01 '26 10:01

Sangeet Agarwal


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.

like image 34
markerikson Avatar answered Jan 01 '26 08:01

markerikson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!