React Js and Redux: useSelector() vs useStore()
I Would Like to Know What Is the Difference Between useSelector and Usestore. Are There Any Advantages on Using One Instead of the Other? Thanks. useSelector...
I would like to know what is the difference between useSelector and UseStore. Are there any advantages on using one instead of the other? Thanks.
useSelector
const { pages } = useSelector((state: RootState) => {
return {
pages: state.pages
};
});
console.log(pages);
useStore
const pageArrayTwo = useStore();
const pageArray = pageArrayTwo.getState().pages;
console.log(pageArray);
Same Output On Both Cases
[{…}]
0: {id: 1, title: "Use Redux", content: "Welcome"}
length: 1
__proto__: Array(0)
2 Answers
UseSelector, the main advantage here is that it does a shallow comparison of the previous selector result, thus potentially not re-rendering if the result would be the same.
When an action is dispatched,
useSelector()will do a reference comparison of the previous selector result value and the current result value. If they are different, the component will be forced to re-render. If they are the same, the component will not re-render.
useStore just gets you access to the store object, do any component logic based on accessing the store's state won't benefit from this check. In fact, redux even recommends against using it for this purpose.
This hook should probably not be used frequently. Prefer
useSelector()as your primary choice. However, this may be useful for less common scenarios that do require access to the store, such as replacing reducers.
useSelector: This is just a simple function, which takes in a function that takes the state as an argument and returns a value. Used to get a single value from state. Can act as a replacement for mapStateToProps.
useDispatch: returns a reference to the dispatch object. It can act as a replacement for mapDispatchToProps.
useStore: returns an instance of the store. Generally not recommended, because the component which uses this will not get updated. In such case use have to use react hooks like useEffect o explicitly update the component.
Please the sample here which is posted on other stack instance other stackoverflow instance