reactjsredux

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

  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)

Solution

  • 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.